React-如何将局部变量传递给子组件

时间:2018-11-09 15:49:01

标签: reactjs

很不幸,我正在运行React 15.6,我无权访问新的"city": "London" 函数。

无论如何,这是我的组件。我在组件中有一个名为React.creatRef的局部变量,我将其作为newPass连接到inputRef中。当用户键入密码时,FormControl会填入键入的内容。

newPass

现在,我想将export class ResetForm extends React.Component { render() { let newPass; return ( <div> <FormGroup> <ControlLabel>New Password</ControlLabel> <FormControl type="password" onChange={() => { if (newPass) { // validate the password } }} inputRef={(ref) => newPass = ref} /> </FormGroup> <SaveButton {...this.props} newPass={newPass} /> </div> ); } } 的值发送到子组件newPass中。

SaveButton

但是,在测试时,我输入表单并单击“保存”按钮,在export class SaveButton extends React.Component { render() { return ( <Button onClick={() => this.props.doTheSave(this.props.newPass.value);}> Save </Button> ); } } 行上出现错误,提示:doTheSave。子组件似乎不知道Cannot read value of undefined是什么。谁能告诉我如何将局部变量的结果传递到子组件中?

2 个答案:

答案 0 :(得分:1)

您可以control the input并在每次更改时将新的输入值存储在状态中,然后将其提供给SaveButton组件。

示例

class ResetForm extends React.Component {
  state = {
    newPass: ""
  };

  onChange = event => {
    this.setState({ newPass: event.target.value });
  };

  render() {
    const { newPass } = this.state;

    return (
      <div>
        <FormGroup>
          <ControlLabel>New Password</ControlLabel>
          <FormControl type="password" value={newPass} onChange={this.onChange} />
        </FormGroup>
        <SaveButton {...this.props} newPass={newPass} />
      </div>
    );
  }
}

class SaveButton extends React.Component {
  render() {
    return (
      <Button onClick={() => this.props.doTheSave(this.props.newPass)}>
        Save
      </Button>
    );
  }
}

答案 1 :(得分:0)

newPassword应该像这样保存newPass的引用值:

export class ResetForm extends React.Component {
render() {
    let newPass;

    return (
        <div>
            <FormGroup>
                <ControlLabel>New Password</ControlLabel>
                <FormControl
                    type="password"
                    onChange={() => {
                        if (newPass) {
                            // validate the password
                        }
                    }}
                    inputRef={(ref) => newPass = ref} />
            </FormGroup>
            <SaveButton {...this.props} newPassword={newPass} />
        </div>
    );
}

}