反应,通过道具将数据从孩子传递到父母

时间:2019-12-17 18:09:32

标签: reactjs

我有两个组成部分:

在父组件中:

handleSubmit= (val) => {
    console.log(val)//hello
    console.log("but I also needs the value of indexTab here, I just have the parameter val")
    console.log(indexTab) <---
}

render() {
    const val =" hello"

    return(
        <Child
            handleOnSubmit = {() => this.handleSubmit(val)}
            etc...

在孩子中,我有

class Child extends Component<Props> {

  render() {

    const { indexTab } = this.props;

    return (<Button onClick={handleSubmit}> {indexTab !== 2 ? "Save 0 or 1" : "Save 2"} </Button>
    );
  }
}

我需要在父亲中使用indexTab中的handleSubmitSaveConfigurationsPre值,如何通过道具onClick={handleSubmit}传递该值?

3 个答案:

答案 0 :(得分:1)

handleSubmit作为参数调用包装在匿名函数中的indexTab

<Button onClick={() => handleOnSubmit(indexTab)}>

父项

<Child
            handleOnSubmit = {(indexTab) => this.handleSubmit(val, indexTab)}
            etc...

答案 1 :(得分:1)

在父母中,您应该做类似的事情。

class Parent extends React.Component {
state = {
   tabIndex: null
}

handleSubmitSaveConfigurationsPre = val => {
    console.log(val);
    console.log(this.state.tabIndex);
}

setValuleFromChild = value => {
  this.setState({tabIndex: value });
}

<Child handleOnSubmit={this.setValuleFromChild} ...

在孩子们中,您应该做类似的事情:

render() {

    const { indexTab,  handleSubmit} = this.props;

    return (<Button onClick={() => handleSubmit(indexTab)}> {indexTab !== 2 ? "Save 0 or 1" : "Save 2"} </Button>
    );

答案 2 :(得分:0)

首先要将附加参数传递给handleSubmit,您需要更改函数的签名

handleSubmit= (val, foo) => {
    console.log(val)//hello
    console.log(foo)
}

现在准备将callback传递给您的Child,以期望有附加参数

return <Child callback={foo => this.handleSubmit(val, foo)} />

然后从Child内部调用您的callback

callback('foo')