将道具从孩子传递给父母不工作(反应)

时间:2019-03-31 11:59:00

标签: javascript reactjs

我有来自输入的<form>值的子组件。需要在父组件中传递和呈现。具有onSubmit方法,该方法适用于子级,但似乎不适用于父级组件。 怎么了?

我正在尝试在<input>(父级)中渲染<h1>(子级)的值。

Child.js

   state = {
     title : ''
   }
  onSubmit = (e) => {
    e.preventDefault();
    this.props.textChange(this.state.title);
    this.setState({ title: '' });
  };

   onChange = (e) => this.setState({ title: e.target.value });


  render() {
    return (
      <div>
      <form 
        onSubmit={this.props.onSubmit}>
        <input 
          type="text" 
          name="title"
          placeholder="your tex here..."
          value={this.state.title}
          onChange={this.onChange}
        />

        <input 
        type="submit"
        value ="Submit"
        />
        </form>
      </div>
    )
  }
}
export default Text

Parent.js

class App extends Component {
  state = {
    colors: [],
    text: 'title'
  };

textChange = (title) => {
  console.log(title);
  this.setState({ text: title });
}

 return (
    <div className="App">
      <h1 className="title">{this.state.text}</h1>
      <Text textChange={this.textChange}/>
    </div>

4 个答案:

答案 0 :(得分:3)

props用于访问父方法/值

{this.props.onSubmit}更改为{this.onSubmit},因为onSubmit是孩子的方法

答案 1 :(得分:1)

props中删除onSubmit={this.props.onSubmit}。道具用于从父级访问数据。在这种情况下,onSubmit函数位于Child.js文件而非Parent.js文件的本地。

state = {
  title: ''
}
onSubmit = (e) => {
  e.preventDefault();
  this.props.textChange(this.state.title);
  this.setState({
    title: ''
  });
};

onChange = (e) => this.setState({
  title: e.target.value
});


render() {
  return ( <
    div >
    <
    form onSubmit = {
      this.onSubmit // REMOVED .props
    } >
    <
    input type = "text"
    name = "title"
    placeholder = "your tex here..."
    value = {
      this.state.title
    }
    onChange = {
      this.onChange
    }
    />

    <
    input type = "submit"
    value = "Submit" /
    >
    <
    /form> < /
    div >
  )
}
}
export default Text

答案 2 :(得分:1)

您正在尝试从道具中调用onSubmit方法,并将此方法放在子组件中。相反,您应该直接在this对象上调用它。像这样:

<form 
  onSubmit={this.onSubmit}>

答案 3 :(得分:0)

您正在访问未传递给子组件的道具,则应将this.props.onSubmit更改为this.onSubmit。

state = {
     title : ''
   }
  onSubmit = (e) => {
    e.preventDefault();
    this.props.textChange(this.state.title);
    this.setState({ title: '' });
  };

   onChange = (e) => this.setState({ title: e.target.value });


  render() {
    return (
      <div>
      <form 
        onSubmit={this.onSubmit}>
        <input 
          type="text" 
          name="title"
          placeholder="your tex here..."
          value={this.state.title}
          onChange={this.onChange}
        />

        <input 
        type="submit"
        value ="Submit"
        />
        </form>
      </div>
    )
  }
}
export default Text