React Native中如何将组件的一个prop值传入同一组件的另一个prop?
解决组件prop在style中未定义的问题
你遇到的核心问题是作用域混淆:你在<Component>的style属性里写的propOne,属于父组件作用域,但你并没有在父组件中定义这个变量——你只是把true作为propOne的值传给了子组件,这个值并没有在父组件作用域中生成名为propOne的变量。
下面分两种场景给出解决方法:
场景1:父组件中已有propOne变量
如果propOne是父组件里已经定义好的变量,直接在style中使用这个变量即可:
// 父组件内定义变量 const propOne = true; <Component propOne={propOne} style={{ backgroundColor: propOne ? "red" : "blue" }} />
场景2:让子组件根据自身的propOne设置样式
如果是想让<Component>自己根据接收的propOne控制背景色,不能在父组件的style里写逻辑,要把逻辑移到子组件内部:
// 子组件Component的实现 function Component({ propOne, style }) { // 合并外部传入的style和内部生成的样式 const componentStyle = { ...style, backgroundColor: propOne ? "red" : "blue" }; return <div style={componentStyle}>{/* 组件内容 */}</div>; } // 父组件调用时,只需传递propOne(可额外传其他样式) <Component propOne={true} style={{ padding: "12px" }} />
这样就能避免propOne未定义的问题,同时实现根据prop值设置样式的需求。
内容的提问来源于stack exchange,提问作者Anthon Santhez
相关产品推荐
相关产品推荐

