【问题标题】:Value not passing to Parent component [duplicate]值未传递给父组件[重复]
【发布时间】:2019-01-04 11:48:42
【问题描述】:

我正在尝试通过 props 将值从子组件传递给父组件,其中包含一个函数,但它会引发错误 undefined is not a function(evaluating(this.setstate({search: val})) 请问我做错了什么

class Child extends React.Component {
  do() {
    this.props.value("books");
  }
  componentDidMount() {
    this.do();
  }
  render() {
    return <Text>yams</Text>;
  }
}

class Parent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      search: ""
    };
  }
  handleChange = e => {
    this.props.onUpdate(e.target.value);
    this.setState({ search: e.target.value });
  };
  con(val) {
    this.setState({ search: val });
  }
  render() {
    return (
      <View>
        <Child value={this.con} />
        <Text>{this.state.search}</Text>{" "}
      </View>
    );
  }
}

【问题讨论】:

    标签: javascript reactjs react-native


    【解决方案1】:

    您需要.bind 您的函数才能使用this。在您的构造函数中执行此操作或使用箭头函数。

    constructor(props){
        super(props);
        this.state= {
            search: ''
        }
        this.con = this.con.bind(this);
    }
    

    con = val =>
        this.setState({search: val});
    

    【讨论】:

      【解决方案2】:

      con 函数定义为粗箭头函数:

      con = (val) => {
          this.setState({search: val});
      }
      

      这会将this 绑定到父类上下文

      【讨论】:

        猜你喜欢
        • 2020-02-04
        • 2019-01-29
        • 2019-04-28
        • 1970-01-01
        • 2020-09-01
        • 2021-10-19
        • 1970-01-01
        • 2018-05-01
        • 2020-08-06
        相关资源
        最近更新 更多