新增头部搜索组件

在新增组件之前,为了快速的写出好看的页面,我们考虑把bootstrap引入使用。

下载bootstrap

$ npm install bootstrap --save

然后在app/index.js中引入样式文件,代码清单:app/index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Router, browserHistory  } from 'react-router';
import routes from './routes/index.jsx';
import 'bootstrap/dist/css/bootstrap.css';

let root = document.getElementById('app');
ReactDOM.render(
  <Router routes={routes} history={browserHistory} />, root
);

按照我们前面的原型图,我们先把头部搜索表单写好,搜索部分的搜索框和按钮部分,我们可以独立成一个搜索组件SearchGithub,代码清单:app/containers/App/App.jsx

import React from 'react';
import { SearchGithub } from '../../components'

const App = ({children, history}) => {
  return (
    <div className="main-container">
      <nav className="navbar navbar-default" role="navigation">
        <div className="col-sm-7 col-sm-offset-2" style={{marginTop: 15}}>
          <SearchGithub history={history}/>
        </div>
      </nav>
      <div className="container">
        {children}
      </div>
    </div>
  )
}

export default App

同时,我们要在components目录下新建一个SearchGithub组件

$ cd app/components && mkdir SearchGithub
$ cd SearchGithub && touch SearchGithub.jsx

封装我们的SearchGithub组件,代码清单:app/components/SearchGithub/SearchGithub.jsx

import React, { Component, PropTypes } from 'react';
import { browserHistory } from 'react-router';

class SearchGithub extends Component {
  static PropTypes = {
    history: PropTypes.object.isRequired
  }
  getRef(ref){
    this.usernameRef = ref;
  }
  handleSubmit(event){
    const username = this.usernameRef.value;
    this.usernameRef.value = '';

    const path = `/profile/${username}`;
    browserHistory.push(path)

  }
  render(){
    return (
      <div className="col-sm-12">
        <form onSubmit={() => this.handleSubmit()}>
          <div className="form-group col-sm-7">
            <input type="text" className="form-control" ref={(ref) => this.getRef(ref)} />
          </div>
          <div className="form-group col-sm-5">
            <button type="submit" className="btn btn-block btn-primary">搜索 Github</button>
          </div>
        </form>
      </div>
    )
  }
}

export default SearchGithub;

为了便于其他地方获取,我们需要更新components目录下的组件列表文件,代码清单:app/components/index.js

'use strict';

export TestDemo from './TestDemo/TestDemo.jsx';
export SearchGithub from './SearchGithub/SearchGithub.jsx';

哒哒,我们来看一下效果

results matching ""

    No results matching ""