希望我的问题很清楚,我主要在寻找一种将属性动态附加到JSX输入的方法。
<input type="text" {variableAttribute}={anotherVariable} />
在不重写JSX从JS编译为常规HTML的方式的情况下,这样的事情可能吗?
您可以使用计算的属性名称初始化对象,然后使用JSX Spread Attributes将其转换为attribute:
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>
DOCS