What is the best way to have variable attributes in JSX?

落爺英雄遲暮 提交于 2019-12-04 11:13:09

问题


Hopefully my question is clear, I'm mainly looking for a way to dynamically attach attributes to a JSX input.

<input type="text" {variableAttribute}={anotherVariable} />

Is something like this possible without overriding the way JSX compiles to JS to regular HTML?


回答1:


You can initialize an object with a computed property name, and then use JSX Spread Attributes to convert it to attribute:

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



回答2:


You can't do it the way you are doing. You need to define your attributes as object and pass that as spread attributes.

The properties of the object that you pass in are copied onto the component's props.

You can use this multiple times or combine it with other attributes.

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



来源:https://stackoverflow.com/questions/38619182/what-is-the-best-way-to-have-variable-attributes-in-jsx

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!