【问题标题】:What is the best way to have variable attributes in JSX?在 JSX 中拥有可变属性的最佳方式是什么?
【发布时间】:2016-12-01 19:57:16
【问题描述】:

希望我的问题很清楚,我主要是在寻找一种将属性动态附加到 JSX 输入的方法。

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

在不覆盖 JSX 从 JS 编译为常规 HTML 的方式的情况下,这样的事情是否可行?

【问题讨论】:

    标签: reactjs jsx


    【解决方案1】:

    你可以用computed property name初始化一个对象,然后用JSX Spread Attributes把它转换成属性:

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

    【讨论】:

      【解决方案2】:

      你不能按照你现在的方式去做。您需要将属性定义为对象并将其作为传播属性传递。

      你传入的对象的属性被复制到组件的 props 上。

      您可以多次使用它或将其与其他属性结合使用。

      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

      【讨论】:

        猜你喜欢
        • 2015-08-04
        • 1970-01-01
        • 1970-01-01
        • 2014-05-22
        • 1970-01-01
        • 2011-01-29
        • 1970-01-01
        • 1970-01-01
        • 2021-07-06
        相关资源
        最近更新 更多