将函数作为道具传递给子功能组件

时间:2021-04-28 15:26:02

标签: reactjs typescript

我正在尝试将回调函数传递给作为功能组件的子组件,以便它可以更新父组件。我在孩子内部收到一个错误 Uncaught TypeError: updateVal is not a function(我将在它发生的行中添加注释)。知道我做错了什么吗?

export default class Parent extends React.Component {
  constructor(props: any) {
    super(props);

    this.updateVal = this.updateVal.bind(this);

    this.state = {
      val: 'A',
    };
  }
  
  updateVal(newVal: string) {
    this.setState({ val: newVal });
  }

  render() {
    return (
      <Child 
        updateVal={this.updateVal}
      />
    );
  };
}
export function Child(updateVal: any) {
  
  const handleSelectorChange = (event: any) => {
    updateVal(event.target.value); // error here: updateVal is not a function
  };

  return (
      <Select onChange={handleSelectorChange} >
        <option value="A">A</option>
        <option value="B">B</option>
      </Select>
  );
};

2 个答案:

答案 0 :(得分:0)

Child(updateVal: any) 中的问题。您需要更新它:Child({updateVal}: any)

答案 1 :(得分:0)

Props 作为对象传递给功能组件,而不是作为单独的参数。简而言之,鉴于 JSX:

<Child
  foo={fooValue}
  bar={barValue}
/>

您可以期望孩子收到一个在其 props 中包含 { foo: fooValue, bar: barValue } 的对象。

功能组件的第一个参数是该对象。您可以直接从中检索所需的值:

export function Child(props) {
  const updateVal = props.updateVal;
  // ...
}

或通过destructing it

export function Child({ updateVal }) {
  // ...
}