【问题标题】:Passing props to hook components getting undefined将道具传递给未定义的钩子组件
【发布时间】:2020-03-13 13:39:17
【问题描述】:

如何在两个钩子组件中传递道具?

我有一个使用Modal 的根组件,我需要将道具title 传递给我的Modal 组件并在组件中显示:

<Modal title="test" />

在模态组件中,我接收道具作为参数:

const Modal = (title) => {

return (
    <h6>{title}</h6>
)

但我收到未定义的消息。

我也尝试过使用 {}:

const Modal = ({title}) => {

为什么?

【问题讨论】:

  • const Modal = (props) =&gt; { console.log(props.title)
  • const Modal = ({title}) => {} 应该可以工作
  • 是的,我正在这样做@Domino987,但在我的 useEffect 中打印未定义:useEffect(() => { console.log(props.title) }, []); // eslint-disable-line

标签: reactjs react-hooks


【解决方案1】:

需要在子组件中引用props对象:

const Modal = (props) => {

return (
    <h6>{props.title}</h6>
)

或者通过解构:

const Modal = ({title}) => {

return (
    <h6>{title}</h6>
)

【讨论】:

  • 我尝试了这两种方法,但都在安慰 undefined
  • 那么你可能做错了一些基本的事情。你需要编辑你的问题并为我们包括你所有的代码。
  • 你是对的。我正在编辑错误的文件。现在它正在工作
猜你喜欢
  • 2021-11-18
  • 2021-01-16
  • 2019-07-11
  • 2023-04-08
  • 2020-07-03
  • 2020-09-01
  • 2018-07-07
  • 2021-11-10
  • 2019-11-17
相关资源
最近更新 更多