值未传递给父组件

时间:2018-07-27 10:54:46

标签: javascript reactjs react-native

我正在尝试通过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>
    );
  }
}

2 个答案:

答案 0 :(得分:3)

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

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

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

答案 1 :(得分:1)

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

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

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