我有这个 TextField 元素。我想有条件地添加 value={x}
或 defaultValue={x}
这将起作用(没有任何条件)
<TextField
id="pickupName"
className="order-form-input"
onBlur={this.fieldChange('name')}
ref="pickupName"
defaultValue={(order.pickup || {}).name || ''}
// hintText="Pickup Contact Name"
floatingLabelFixed={true}
floatingLabelText="Contact Name"
/>
但是,如果我尝试添加条件(当然会失败):
<TextField
id="pickupName"
className="order-form-input"
onBlur={this.fieldChange('name')}
ref="pickupName"
{true ? defaultValue={(order.pickup || {}).name || ''} :
value={(order.pickup || {}).name || ''}}
// hintText="Pickup Contact Name"
floatingLabelFixed={true}
floatingLabelText="Contact Name"
/>
有没有办法让 defaultValue
或 value
属性指向函数而不是静态字符串?鉴于我的需要,我必须有条件地使用 value
或 defaultValue
,因为它们的行为完全不同。
最佳答案
如果您使用的是 es6,您可以使用 {...args}
运算符解析组件声明末尾的所有剩余参数。
示例:
<TextField
id="pickupName"
className="order-form-input"
onBlur={this.fieldChange('name')}
ref="pickupName"
floatingLabelFixed={true}
floatingLabelText="Contact Name",
{...extra_args}
/>
希望它能起作用。
关于javascript - 使用 React 有条件地从元素中添加/删除属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41116891/