简体   繁体   English

无法将 function 传递给 React 中的子组件

[英]Not able to pass function to child component in React

I don't understand what is happening, the syntax seems to be right, but I'm receiving this error:我不明白发生了什么,语法似乎是正确的,但我收到此错误:

TypeError: chooseMessage is not a function TypeError: chooseMessage 不是 function

// PARENT COMPONENT

import React, { useState } from 'react'


export default function LayoutMain(props) {

    const [message, setMessage] = useState("Hello World");

    const chooseMessage = (message) => {
        setMessage(message);
    };


    return (
        
        <div>
            <LayoutMenu>
                 <Navigator chooseMessage={chooseMessage} />
            </LayoutMenu>
        </div>
    )
}



//CHILDREN COMPONENT

export default function Navigator({chooseMessage}) {
   
    let msg = 'Goodbye';
    
    return (
  
            <div className='navigator-header' onClick={() => chooseMessage(msg)}>
                 test
            </div>
    )
}

I've read articles about lifting state up and also watched some videos and followed the instructions carefully over and over again but had no success.我已经阅读了有关将 state 抬高的文章,还观看了一些视频,并一遍又一遍地仔细按照说明进行操作,但没有成功。

#NEW UDPATE #新更新

I just realized that my code is definitively correct, it must be something related to the compiler or something.我刚刚意识到我的代码绝对正确,它必须与编译器或其他东西有关。

You could pass setMessage from the parent down to the child, then you can use the message state in the parent, and pass message down to the child if you want to use it in the child as well.您可以将 setMessage 从父级传递给子级,然后您可以在父级中使用消息 state,如果您也想在子级中使用它,则可以将消息传递给子级。

export default function LayoutMain (props) {
    const [message, setMessage] = useState('Hello World');

    return (
        <div>
            <LayoutMenu>
                <Navigator setMessage={setMessage} />
            </LayoutMenu>
            <p>{ message }</p>
        </div>
    )
}

export default function Navigator({ setMessage }) {
    const chooseMessage = (message) => {
        setMessage(message);
    };
    
    return (
        <div className='navigator-header' onClick={() => chooseMessage('Goodbye')}>
            test
        </div>
    )
}

Seems like the code is working fine.似乎代码工作正常。 However, you can control all the logic from one component that can be a parent controller and expose methods as props to interact with them it will be easier to manage the state there.但是,您可以从一个可以作为父组件 controller 的组件控制所有逻辑,并将方法公开为与它们交互的道具,在那里管理 state 会更容易。

https://codesandbox.io/s/tender-smoke-57v1bk?file=/src/App.js https://codesandbox.io/s/tender-smoke-57v1bk?file=/src/App.js

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM