问题描述
利用 props 向元素传递 value 值:
const Element1 = () => {
return <Element2 value="something" />;
}
调用 value:
const Element2 = (props) => {
console.log(props.value);
return <div />;
}
发现结果为 undefined,而不是预期的 something.
定位问题
调用 props:
const Element2 = (props) => {
console.log(props);
return <div />;
}
结果为:
{
id: "nest-messages_LocationDesc"
onChange: ƒ ()
value: undefined
[[Prototype]]: Object
}
因此 props 组件正常地传递了,只是 props.value 出了问题。
尝试使用不同的 key 传递:
const Element1 = () => {
return <Element2 someKey="something" />;
}
调用 someKey:
const Element2 = (props) => {
console.log(props.someKey);
return <div />;
}
结果为:
{
someKey: "something"
id: "nest-messages_LocationDesc"
onChange: ƒ ()
value: undefined
[[Prototype]]: Object
}
因此笔者推测,props 预留了 value 字段,因此传递 props.value 会出现问题。
解决方法
不要使用 props.value,使用一个别的名字。
避免Props值冲突
本文探讨了在React中使用props传递值时遇到的问题,当尝试通过props.value传递数据时出现了未定义的情况。通过调整key名称成功解决了该问题。
1176

被折叠的 条评论
为什么被折叠?



