How to create a dynamic prop name in React?

后端 未结 3 642
谎友^
谎友^ 2021-01-31 15:34

Is it possible to create the name of a prop dynamically? For example:

let dynamicPropName = \"someString\";

         


        
相关标签:
3条回答
  • 2021-01-31 15:51

    An inline way (very ugly and not recommended) is using a expression to define an object:

    <input {...(el.required ? {required: true} : {})}>
    
    0 讨论(0)
  • 2021-01-31 15:54

    If you are using es6, you can define the dynamic prop:

    let dynamicProps = {"dynamicKey":"someString", "dynamicKey2":"someString"};
    

    or

    let someVariable = "xyz";
    dynamicProps[someVariable] = value;
    

    then use the spread operator:

    <MyComponent {...dynamicProps} />
    

    Inside MyComponent -

    let props = {...this.props};
    

    Now you can use Object.keys on props to get all dynamic prop names.

    Edit: Added an example

    class Test extends React.Component {
      
      renderFromProps() {
        return Object.keys(this.props)
        .map((propKey) =>
          <h3>{this.props[propKey]}</h3>
        );
      }
      render() {
        return (
         <div>
          <h1>One way </h1>
          <hr/>
          <h3>{this.props.name}</h3>
          <h3>{this.props.type}</h3>
          <h3>{this.props.value}</h3>
          <hr/>
         <h1> Another way </h1>
          <hr/>
          { this.renderFromProps()}
         </div>
       );
      }
      
    }
    
    const dynamicProps = { name:"Test", type:"String", value:"Hi" };
    
    ReactDOM.render(
      <Test {...dynamicProps} />,
      document.getElementById('root')
    );
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
    <div id="root">
    </div>

    0 讨论(0)
  • 2021-01-31 15:58

    It's possible to do this with JSX syntax alone with spread attribute and computed property name:

    <MyComponent {...{ [dynamicPropName]: "some value" }} />
    
    0 讨论(0)
提交回复
热议问题