我在某个项目中使用React.js,我只想在条件为真的时候发送道具,我不想要的发送空值或空的东西为以下示例(或this question):
return (
<SomeComponent
prop1={foo === true ? "value" : null}
/>
);
如果条件为真,我想发送整个道具(不仅是它的值),如下所示:
render: function(){
...
return (
<SomeComponent
{if(foo === true) prop1="value"}
/>
);
}
我也试过
...
var prop1;
if(foo === true) prop1 = "prop1='value'";
return <SomeComponent {prop1} />;
当然还有像
这样的东西 ...
return (
</SomeComponent
{foo === true ? prop1="value" : ""}
/>
);
在所有情况下,我都遇到Unexpected token
错误,我一直在寻找,但我找不到任何东西,有没有办法做出反应呢?
感谢。
答案 0 :(得分:1)
虽然不确定目的是什么 - 使用ES6传播操作符,你可以这样做:
const props = {};
if (foo === true) { // or just if (foo) {
props.prop1 = 'value';
}
<SomeComponent
{ ...props } />
答案 1 :(得分:1)
即使您发送未定义的值,您也将始终拥有 有机会验证两个函数中的任何一个: componentWillMount 对于第一次加载或第一次加载后 componentWillReceiveProps 。 此外,您始终可以使用渲染功能进行验证。但如果我 按照你正在尝试的方法回答。
render : function(){
if(foo === true)
return <SomeComponent prop1 ="value1" />;
else
return <SomeComponent />;
}
在渲染组件中,您可以使用 getDefaultProps 函数 如果您未传递任何道具值,则设置默认值 你的第二个案例。