How to dynamically add properties based on conditions in React components?
P粉665427988
P粉665427988 2023-08-20 14:54:00
0
2
540

Is there a way to add properties to a React component only when certain conditions are met?

I need to add required and readOnly attributes to the form element based on conditions in the post-rendered Ajax call, but I don't know how to solve this problem because readOnly="false" is completely different from Omitting attributes is different.

The example below should illustrate what I want, but it doesn't work.

(Parse error: unexpected identifier)

function MyInput({isRequired}) { return  } 


P粉665427988
P粉665427988

reply all (2)
P粉545218185

juandemarco's answeris usually correct, but there is another option here.

Construct an object to your liking:

var inputProps = { value: 'foo', onChange: this.handleChange }; if (condition) { inputProps.disabled = true; }

Use spread for rendering, and you can also choose to pass other props.

    P粉863295057

    Obviously, for some properties, if the value passed to React is not a true value, React will intelligently omit the property. For example:

    const InputComponent = function() { const required = true; const disabled = false; return (  ); }

    will get:

    UPDATE:If anyone is curious about how and why this happens, you can find the details in the source code of ReactDOM, specifically in theDOMProperty.jsfile at page 30 Lines and167 lines.

      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!