I would like to know if there is a better way to conditionally pass a prop than using an if-statement.
我想知道是否有一种更好的方式来有条件地传递道具而不是使用if语句。
For example, right now I have:
例如,我现在有:
var parent = React.createClass({
propTypes: {
editable: React.PropTypes.bool.isRequired,
editableOpts: React.PropTypes.shape({...})
},
render: function() {
if(this.props.editable) {
return (
<Child editable={this.props.editableOpts} />
);
} else {
// In this case, Child will use the editableOpts from its own getDefaultProps()
return (
<Child />
);
}
}
});
Is there a way to write this without the if-statement? I am was thinking something along the lines of a type of inline-if-statement in the JSX:
有没有办法在没有if语句的情况下写这个?我正在考虑JSX中一种内联if语句的内容:
var parent = React.createClass({
propTypes: {
editable: React.PropTypes.bool.isRequired,
editableOpts: React.PropTypes.shape({...})
},
render: function() {
return (
<Child
{this.props.editable ? editable={this.props.editableOpts} : null}
/>
);
}
});
To wrap-up: I'm trying to find a way to define a prop for Child
, but pass a value (or do something else) such that Child
still pulls that prop's value from Child
's own getDefaultProps()
.
总结:我正试图找到一种方法为Child定义道具,但传递一个值(或做其他事情),使Child仍然从Child自己的getDefaultProps()中提取该道具的值。
57
You were close with your idea. It turns out that passing undefined
for a prop is the same as not including it at all, which will still trigger the default prop value. So you could do something like this:
你接近你的想法。事实证明,传递未定义的道具与完全不包括它相同,这仍将触发默认道具值。所以你可以这样做:
var parent = React.createClass({
propTypes: {
editable: React.PropTypes.bool.isRequired,
editableOpts: React.PropTypes.shape({...})
},
render: function() {
return <Child
editable={this.props.editable ?
this.props.editableOpts :
undefined}
/>;
}
});
3
Define props
variable:
定义道具变量:
let props = {};
if (this.props.editable){
props.editable = this.props.editable;
}
And then use it in JSX:
然后在JSX中使用它:
<Child {...props} />
Here is a solution in your code:
以下是代码中的解决方案:
var parent = React.createClass({
propTypes: {
editable: React.PropTypes.bool.isRequired,
editableOpts: React.PropTypes.shape({...})
},
render: function() {
let props = {};
if (this.props.editable){
props.editable = this.props.editable;
}
return (
<Child {...props} />
);
}
});
Source, React documentation: https://facebook.github.io/react/docs/jsx-in-depth.html#spread-attributes
来源,反应文档:https://facebook.github.io/react/docs/jsx-in-depth.html#spread-attributes
0
add a spread operator to the this.props.editable
将扩展运算符添加到this.props.editable
<Child {...this.props.editable ? editable={this.props.editableOpts} : null} >
should work
-1
const CleaningItem = ({ disabled = false }) => (
<View
style={[styles.container, disabled && styles.disabled]}
pointerEvents={disabled ? 'none' : 'auto'}
>
<Button
disabled={disabled || null}
title="SELECT"
/>
</View>
);
本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.silva-art.net/blog/2015/08/26/a8ac36258bc054bf194a8839132cc60d.html。