【问题标题】:Pass data via on click from child component to parent component react通过点击从子组件传递数据到父组件反应
【发布时间】:2021-12-24 03:48:20
【问题描述】:

我是 React 新手,正在尝试将数据(director、nonDirector)从我的子功能组件传递到父类组件。

我的代码如下,我需要做什么才能让它工作?

类父组件

export default class ProfileEditor extends React.Component<IProfileEditorProps, IProfileEditorState> {
    
      constructor(props: IProfileEditorProps) {
        super(props);
        this.state = {
          data: null,
        }
         this.updateProfile = this.updateProfile.bind(this);
      }

    public updateProfile(director, nonDirector) {

        console.log('hello', director, nonDirector);

     }

      <MultiSelect
        options={ profile?.Declarations.length == 0 ? countries : this.combineProfileAndCountrys() }   
        updateProfile={updateProfile()}
      />

子功能组件

export const MultiSelect = ({ options, updateProfile }) => { 

const [nonDirector, setNonDirector] = React.useState();
const [director, setDirector] = React.useState();

<PrimaryButton text='Save' onClick={ updateProfile(nonDirector, director) } />
    </Fragment>
);

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    在您的父组件中,您不应该在 onClick 处理程序中调用该函数。您想将 reference 传递给该函数。

    updateProfile={updateProfile}
    

    您的子组件中也出现了类似问题。您不想调用该函数并将其结果返回给处理程序,您希望将一个函数分配给处理程序,然后在其触发时调用updateProfile 函数。

    onClick={() => updateProfile(nonDirector, director)}
    

    【讨论】:

    • 谢谢安迪!
    猜你喜欢
    • 2019-10-13
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 2016-09-05
    • 2020-03-04
    • 1970-01-01
    • 2019-02-27
    相关资源
    最近更新 更多