在 JSX 中拥有可变属性的最佳方式是什么?
What is the best way to have variable attributes in JSX?
希望我的问题很清楚,我主要是在寻找一种将属性动态附加到 JSX 输入的方法。
<input type="text" {variableAttribute}={anotherVariable} />
是否可以在不覆盖 JSX 从 JS 编译为常规 HTML 的方式的情况下实现这样的事情?
您可以使用 computed property name, and then use JSX Spread Attributes 初始化对象以将其转换为属性:
const DemoComponent = ({ variablePropName, variablePropValue }) => {
const variableAttribute = { [variablePropName]: variablePropValue };
return (
<input type="text" { ...variableAttribute } />
);
};
你不能按照你现在的方式去做。您需要将属性定义为对象并将其作为传播属性传递。
您传入的对象的属性被复制到组件的道具上。
您可以多次使用它,也可以将它与其他属性结合使用。
var Hello = React.createClass({
render: function() {
var opt = {}
opt['placeholder'] = "enter text here";
return (<div>
Hello {this.props.name}
<div>
<input type="text" {...opt}/>
</div></div>);
}
});
ReactDOM.render(
<Hello name="World" />,
document.getElementById('container')
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.min.js"></script>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
希望我的问题很清楚,我主要是在寻找一种将属性动态附加到 JSX 输入的方法。
<input type="text" {variableAttribute}={anotherVariable} />
是否可以在不覆盖 JSX 从 JS 编译为常规 HTML 的方式的情况下实现这样的事情?
您可以使用 computed property name, and then use JSX Spread Attributes 初始化对象以将其转换为属性:
const DemoComponent = ({ variablePropName, variablePropValue }) => {
const variableAttribute = { [variablePropName]: variablePropValue };
return (
<input type="text" { ...variableAttribute } />
);
};
你不能按照你现在的方式去做。您需要将属性定义为对象并将其作为传播属性传递。
您传入的对象的属性被复制到组件的道具上。
您可以多次使用它,也可以将它与其他属性结合使用。
var Hello = React.createClass({
render: function() {
var opt = {}
opt['placeholder'] = "enter text here";
return (<div>
Hello {this.props.name}
<div>
<input type="text" {...opt}/>
</div></div>);
}
});
ReactDOM.render(
<Hello name="World" />,
document.getElementById('container')
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.min.js"></script>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>