javascript - 值未传递给父组件

标签 javascript reactjs react-native

<分区>

我试图通过 Prop 将一个值从子组件传递到父组件,其中有一个函数但它抛出错误 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>
    );
  }
}

最佳答案

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

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

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

关于javascript - 值未传递给父组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51556493/

相关文章:

javascript - 无法从包含 milisec '2015-05-14 08:08:48.792' 的日期创建新的 Date() 对象

javascript - 带有 div 标签的 TinyMCE?

html - 如何在 react-bootstrap 中将容器居中?

javascript - 渲染动态 ListView 并将 key 传递给方法

javascript - SessionStorage 似乎仍为空

javascript - Moment.js 获取 dd :hh:mm:ss format? 中两个日期之间的差异

node.js - 何时在 docker 中将 localhost 替换为服务名称?

javascript - 已获取数据但未更新状态

react-native - 如何在全屏 react-native android 中播放视频

react-native - 你如何在 react-native-gifted-chat 中自动聚焦输入框