我有一个父组件,它将一个 prop 传递给子组件。当我尝试通过 prop.a.name 或 prop.a.avatar 访问 prop 时。我从流程中收到以下错误:
property name
无法在未知类型的属性 a
上访问属性
property name
无法通过可能未定义的值访问属性
这是父级的部分
const items = (authors, authorId) => {
const author = authors.find(a => a.id === authorId)
const info = {
name: author ? author.name : '',
profileImage: author ? author.profileImage : '',
company: author ? author.company : '',
}
return info
}
现在,如果我返回 info.name 或 info.profileImage 它会通过,但我想将此对象传递给子组件,以便我可以访问子组件中需要的位置。
这是 child
type Props = {
info: string
}
const child = (props: Props) => {
... some code
<h1>{props.info.name}</h1>
}
最佳答案
尝试:
const items = ({authors, authorId}) => {
const author = authors.find(a => a.id === authorId)
const info = {
name: author ? author.name : '',
profileImage: author ? author.profileImage : '',
company: author ? author.company : '',
}
return info
}
这是因为作者和authorId需要从props对象中提取。
关于javascript - 在子 react 流程中访问对象 Prop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48580966/