Javascript 如何有条件地向 React 组件添加属性?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31163693/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I conditionally add attributes to React components?
提问by Remi Sture
Is there a way to only add attributes to a React component if a certain condition is met?
有没有办法只在满足特定条件时向 React 组件添加属性?
I'm supposed to add required and readOnly attributes to form elements based on an Ajax call after render, but I can't see how to solve this since readOnly="false" is not the same as omitting the attribute completely.
我应该在渲染后基于 Ajax 调用向表单元素添加 required 和 readOnly 属性,但我不知道如何解决这个问题,因为 readOnly="false" 与完全省略属性不同。
The example below should explain what I want, but it won't work (Parse Error: Unexpected identifier).
下面的示例应该解释我想要什么,但它不起作用(解析错误:意外标识符)。
var React = require('React');
var MyOwnInput = React.createClass({
render: function () {
return (
<div>
<input type="text" onChange={this.changeValue} value={this.getValue()} name={this.props.name}/>
</div>
);
}
});
module.exports = React.createClass({
getInitialState: function () {
return {
isRequired: false
}
},
componentDidMount: function () {
this.setState({
isRequired: true
});
},
render: function () {
var isRequired = this.state.isRequired;
return (
<MyOwnInput name="test" {isRequired ? "required" : ""} />
);
}
});
采纳答案by juandemarco
Apparently, for certain attributes, React is intelligent enough to omit the attribute if the value you pass to it is not truthy. For example:
显然,对于某些属性,如果传递给它的值不真实,React 足够智能以省略该属性。例如:
var InputComponent = React.createClass({
render: function() {
var required = true;
var disabled = false;
return (
<input type="text" disabled={disabled} required={required} />
);
}
});
will result in:
将导致:
<input type="text" required>
Update:if anyone is curious as to how/why this happens, you can find details in ReactDOM's source code, specifically at lines 30and 167of the DOMProperty.jsfile.
更新:如果有人对如何/为什么发生这种情况感到好奇,您可以在 ReactDOM 的源代码中找到详细信息,特别是在DOMProperty.js文件的第30和167行。
回答by Brigand
juandemarco's answeris usually correct, but here is another option.
juandemarco 的回答通常是正确的,但这是另一种选择。
Build an object how you like:
以您喜欢的方式构建对象:
var inputProps = {
value: 'foo',
onChange: this.handleChange
};
if (condition)
inputProps.disabled = true;
Render with spread, optionally passing other props also.
渲染传播,也可以选择传递其他道具。
<input
value="this is overridden by inputProps"
{...inputProps}
onChange={overridesInputProps}
/>
回答by Arman Yeghiazaryan
Here is an example of using Bootstrap's Button
via React-Bootstrap(version 0.32.4):
下面是使用的示例自举的Button
经由阵营的自举(版本0.32.4):
var condition = true;
return (
<Button {...(condition ? {bsStyle: 'success'} : {})} />
);
Depending on the condition, either {bsStyle: 'success'}
or {}
will be returned. The spread operator will then spread the properties of the returned object to Button
component. In the falsy case, since no properties exist on the returned object, nothing will be passed to the component.
根据不同的条件,无论是{bsStyle: 'success'}
或{}
将被退回。然后,扩展运算符会将返回对象的属性扩展到Button
组件。在 falsy 情况下,由于返回的对象上不存在任何属性,因此不会将任何内容传递给组件。
An alternative way based on Andy Polhill's comment:
基于Andy Polhill 评论的另一种方式:
var condition = true;
return (
<Button bsStyle={condition ? 'success' : undefined} />
);
The only small difference is that in the second example the inner component <Button/>
's props
object will have a key bsStyle
with a value of undefined
.
唯一的小区别是在第二个示例中,内部组件<Button/>
的props
对象将具有bsStyle
一个值为 的键undefined
。
回答by Season
Here is an alternative.
这是一个替代方案。
var condition = true;
var props = {
value: 'foo',
...( condition && { disabled: true } )
};
var component = <div { ...props } />;
Or its inline version
或者它的内联版本
var condition = true;
var component = (
<div
value="foo"
{ ...( condition && { disabled: true } ) } />
);
回答by Tony Tai Nguyen
Here's a way I do it.
这是我的一种方法。
With a conditional:
有条件的:
<Label
{...{
text: label,
type,
...(tooltip && { tooltip }),
isRequired: required
}}
/>
I still prefer using the regular way of passing props down, because it is more readable (in my opinion) in the case of not have any conditionals.
我仍然更喜欢使用传递 props 的常规方式,因为它在没有任何条件的情况下更具可读性(在我看来)。
Without a conditional:
没有条件:
<Label text={label} type={type} tooltip={tooltip} isRequired={required} />
回答by GijsjanB
You can use the same shortcut, which is used to add/remove (parts of) components ({isVisible && <SomeComponent />}
).
您可以使用相同的快捷方式,用于添加/删除(部分)组件 ( {isVisible && <SomeComponent />}
)。
class MyComponent extends React.Component {
render() {
return (
<div someAttribute={someCondition && someValue} />
);
}
}
回答by Mina Luke
Let's say we want to add a custom property (using aria-* or data-*) if a condition is true:
假设我们想在条件为真时添加一个自定义属性(使用 aria-* 或 data-*):
{...this.props.isTrue && {'aria-name' : 'something here'}}
Let's say we want to add a style property if a condition is true:
假设我们想在条件为真时添加一个样式属性:
{...this.props.isTrue && {style : {color: 'red'}}}
回答by snyh
If you use ECMAScript 6, you can simply write like this.
如果你使用 ECMAScript 6,你可以简单地这样写。
// First, create a wrap object.
const wrap = {
[variableName]: true
}
// Then, use it
<SomeComponent {...{wrap}} />
回答by Michael Parker
This should work, since your state will change after the Ajax call, and the parent component will re-render.
这应该可以工作,因为在 Ajax 调用之后您的状态将发生变化,并且父组件将重新呈现。
render : function () {
var item;
if (this.state.isRequired) {
item = <MyOwnInput attribute={'whatever'} />
} else {
item = <MyOwnInput />
}
return (
<div>
{item}
</div>
);
}
回答by Juraj
In React you can conditionally render Components, but also their attributes, like props, className, id, and more.
在 React 中,你可以有条件地渲染组件,也可以渲染它们的属性,比如 props、className、id 等等。
In React it's very good practice to use the ternary operatorwhich can help you conditionally render Components.
在 React 中,使用三元运算符是一个很好的实践,它可以帮助您有条件地渲染组件。
An example also shows how to conditionally render Component and its style attribute.
一个示例还展示了如何有条件地呈现 Component 及其样式属性。
Here is a simple example:
这是一个简单的例子:
class App extends React.Component {
state = {
isTrue: true
};
render() {
return (
<div>
{this.state.isTrue ? (
<button style={{ color: this.state.isTrue ? "red" : "blue" }}>
I am rendered if TRUE
</button>
) : (
<button>I am rendered if FALSE</button>
)}
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>