Reactjs将变量从一个组件传递到另一个组件

时间:2017-03-28 21:50:14

标签: reactjs

我有这样的组件:

class LoginPage extends React.Component{
  constructor(props)  {
    super(props);
    this.state = {submit:''};
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(e) {
    alert('username and password were submitted: ' + this.props.userName + ' and ' + this.props.password);
    e.prevenDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <GetUsername/>
        <GetPassword/>
        <button type="submit">Login</button>
       </form>
    )
  }
}

GetUsername和GetPassword组件从用户输入获取用户名和密码。我的问题是,无论如何我可以将这两个组件的用户名和密码传递给上面的LoginPage组件的handleSubmit方法,这样弹出的警报可以正确显示吗?

2 个答案:

答案 0 :(得分:0)

要实现您的目标,您需要登录表单拥有自己的状态,其中包括用户名和密码。它将具有更新这些字段的实例方法。它会将这些函数传递给相关的子组件,每当它们发生更改时,它们都会使用适当的值调用this.props.onChange。然后,父组件将更新其适当的状态。这是一个例子。

class LoginPage extends React.Component{
  constructor(props)  {
    super(props);
    this.state = {
      submit:'',
      password: '',
      userName: ''

    };
    this.handleSubmit = this.handleSubmit.bind(this);
    this.onUserNameChange = this.onUserNameChange.bind(this);
    this.onPasswordChange = this.onPasswordChange.bind(this);
  }

  onUserNameChange(userName) {
    this.setState({
      userName: userName
    })
  }

  onPasswordChange(password) {
    this.setState({
      password: password
    })
  }

  handleSubmit(e) {
    alert('username and password were submitted: ' + this.state.userName + ' and ' + this.state.password);
    e.prevenDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <GetUsername onChange={onUserNameChange}/>
        <GetPassword onChange={onPasswordChange}/>
        <button type="submit">Login</button>
       </form>
    )
  }
}

这可能需要进行一些调整,如前所述,您需要确保在this.props.onChangeGetUsername组件中正确摄取GetPassword,以便他们调用该函数并通过。中适当的参数。

答案 1 :(得分:0)

您需要将用户名和密码作为LoginPage组件状态的一部分,并在输入更改时更新状态。您可以通过在LoginPage上定义inputChanged函数来执行此操作,该函数作为支柱传递给您的GetUsernameGetPassword组件。

class LoginPage extends React.Component {
  constructor() {
    super();
    this.state = {
      username: '',
      password: ''
    };
  }

  handleSubmit(e) {
    e.prevenDefault();
    alert('username and password were submitted: ' + this.state.userName + ' and ' + this.state.password);
  }

  handleInputChange(name, value) {
    this.setState({
      [name]: value
    });
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <GetUsername onChange={newValue => this.handleInputChange('username', newValue)} />
        <GetPassword  onChange={newValue => this.handleInputChange('password', newValue)} />
        <button type="submit">Login</button>
       </form>
    )
  }

然后,例如

const GetUsername = ({ onChange }) => (
    <input type="text" name="username" onChange={(e) => onChange(e.target.value)} />
);