React Three Fiber函数组件参数传递问题:height值未传入如何解决
修复MyMat组件的参数传递问题
问题出在React函数组件的参数机制上:React函数组件的入参是一个包含所有传入属性的props对象,而非单个的height参数。你原代码里的function MyMat(height),这里的height实际是整个props对象,自然取不到你传入的4。
两种修复方案:
- 方案1:解构props对象
直接从props中解构出height参数,写法更简洁:
function MyMat({ height }) { if(height > 2) { return (<meshStandardMaterial color="#878787" flatShading={true} />) } else if(height > 1) { return (<meshStandardMaterial color="#674942" flatShading={true} />) } return ( <meshStandardMaterial color="black" flatShading={true} /> ) }
- 方案2:直接访问props属性
保留单个props参数,通过props.height获取传入值:
function MyMat(props) { const height = props.height; if(height > 2) { return (<meshStandardMaterial color="#878787" flatShading={true} />) } else if(height > 1) { return (<meshStandardMaterial color="#674942" flatShading={true} />) } return ( <meshStandardMaterial color="black" flatShading={true} /> ) }
你的调用写法<MyMat height={4} />本身是正确的,无需修改,只要组件定义按上述方式调整,就能正确拿到height的值。
内容的提问来源于stack exchange,提问作者jenepix
相关产品推荐
相关产品推荐

