首页 > 解决方案 > 无法将数据传递给子反应组件

问题描述

我对 React 很陌生,所以如果我的问题很愚蠢,我很抱歉,但我被困在这里。我正在尝试将数据从父组件发送到子组件

家长:

export default function Dashboard() {

const [msg, setMSG] = useState<string>("Hello!");

  return (

    <Table message={msg}/>
  );

}

孩子:

export default function Orders(message: string) {
  const classes = useStyles();
  return (
    <React.Fragment>
{message}
</React.Fragment>
  );
}

我收到一个错误:

输入'{消息:字符串;}' 不可分配给类型“字符串”。

标签: reactjsreact-hooks

解决方案


您似乎遇到了类型不匹配的问题 - 这意味着传递给您的子组件的是object

Type '{ message: string; }'

而您的子组件已通过执行此操作将其输入指定为单个string-Orders(message: string)

尝试以下方法,保留类型检查:

 // now `props` is of type object, 
 // with a `key` called `message`, the value of which is of type `string`
 export default function Orders(props: {message: string}) {
  const classes = useStyles();
  return (
    <React.Fragment>
      {props.message}
    </React.Fragment>
  );
}

推荐阅读