无法调用自定义返回组件和状态更新方法吗?

时间:2018-03-23 04:47:38

标签: reactjs react-router

我的名为homeMessage的子组件包含表单和一个输入标记。

import React,{Component} from "react";
import {BrowserRouter as Router, Link, Switch, Route} from "react-router-dom";
import SignUp from './SignUp';
class App extends Component {
  constructor(props){
    super(props);
    this.state = {
      firstName: ''
    };
  }
  inputData = (event) =>
  {
    this.setState({
      [event.target.name]:event.target.value
    });
  }
  submitData = (event) =>
  {
    event.preventDefault();
  }
  render(){
    let homeMessage = () =>
    {
      return(
        <div>
          <form onSubmit={this.submitData}>
            FirstName:
            <input type="text" name="firstName" onChange={this.inputData}/>
            <button type="submit">Submit</button>
          </form>
          <Link to="/src/SignUp">SignUp</Link>
        </div>
      );
    }
    return(
      <Router>
        <div>
          <Route exact path="/" component={homeMessage}/>
          <Route path="/src/SignUp" render={(props)=><SignUp firstName={this.state.firstName}/>}/>
        </div>
      </Router>
    );
  }
}
export default App;

当我用原始返回方法写homeMessage内容的内容时它工作正常,但是当我在每次击键时创建如上所述的自定义返回组件时它会移除我的光标!

1 个答案:

答案 0 :(得分:0)

homeMessage子组件的定义更改为此 -

const homeMessage = (
      <div>
        <form onSubmit={this.submitData}>
          FirstName:
          <input type="text" name="firstName" onChange={this.inputData}/>
          <button type="submit">Submit</button>
        </form>
        <Link to="/src/SignUp">SignUp</Link>
      </div>
  );

这应该可以正常工作。