父级未成功从子级检索数据

时间:2018-01-28 21:47:15

标签: reactjs react-native

我在传递给子组件的父组件中有一个回调函数,该子组件应该在子组件中的提交发生但是没有按预期工作时检索输入。父级没有检索到任何数据。这是我的代码:

父:

class App extends Component {
  constructor(props) {
    super(props)
     this.state = { item: '' }
  }

  getItem(item) {
    this.setState({
      item: item
    })
    console.log(this.state.item);
  }

  render() {
    return (
      <div className="App">
      <Input getItem={this.getItem} />
      <h2>{this.state.item}</h2>
      </div>
    );
  }
}

子:

class Input extends Component {
  constructor(props) {
    super(props)

    this.state = { value: '' }
    this.handleChange=this.handleChange.bind(this);
    this.handleSubmit=this.handleSubmit.bind(this);
  }

  handleChange(e) {
    this.setState({
      value: e.target.value
    })
    console.log(this.state.value)
  }

  handleSubmit(e) {
    {this.props.getItem(this.state.value)};
  }

  render() {
    return (
      <div>
        <form onSubmit={this.handleSubmit}>
          <label>
            <input type="text" name={this.state.value} onChange={this.handleChange} />
          </label>
          <input type="submit" value="+" />
        </form>
      </div>
    )
  }
}

2 个答案:

答案 0 :(得分:1)

解决方案1:

getItem函数中使用胖箭头,如下所示:

getItem = (item) => {
   this.setState({
      item: item
   })
   console.log(this.state.item);
}

解决方案2: 在counstructor中绑定getItem函数,如:

constructor(props) {
 super(props)
 this.state = { item: '' }
 this.getItem = this.getItem.bind(this);
}

解决方案3:

直接在输入中绑定getItem函数:

<Input getItem={this.getItem.bind(this)} />

答案 1 :(得分:0)

您应该将df1上下文绑定到getItem类。

您可以通过

执行此操作
App

或在定义<Input getItem={this.getItem.bind(this)} />

时使用箭头功能

或者像在子组件中那样绑定构造函数中的方法

相关问题