2016-07-27 77 views

回答

9

您可以用computed property name初始化一個對象,然後用JSX Spread Attributes將其轉換爲商品屬性:

const DemoComponent = ({ variablePropName, variablePropValue }) => { 
    const variableAttribute = { [variablePropName]: variablePropValue }; 
    return (
     <input type="text" { ...variableAttribute } /> 
    ); 
}; 
1

你不能做到這一點,你正在做的方式。您需要將您的屬性定義爲對象並將其作爲傳播屬性傳遞。

傳入的對象的屬性被複制到組件的道具上。

您可以多次使用它或將其與其他屬性組合。

var Hello = React.createClass({ 
 
     render: function() { 
 
     
 
     var opt = {} 
 
     opt['placeholder'] = "enter text here"; 
 
     return (<div> 
 
     Hello {this.props.name} 
 
     <div> 
 
     \t <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

相關問題