简体   繁体   中英

React set multiple defaultValue to test input

I want a default value for each different input component but it only works with one default value.

Page:

<InputField nameValue={'name'} />
<InputField productValue={'product 6sd4f'} />
<InputField informationValue={'information 123'} />

Input component:

function InputField({nameValue, productValue, informationValue}) {
 return (
     <div className='inputDiv'>
        <input type="text" placeholder='type info' defaultValue={`${nameValue ? nameValue : ''} ${productValue ? productValue : ''} ${informationValue ? informationValue : ''}`} />
     </div>
 )
}

在此处输入图像描述

it works correctly? can you attach your issue?

I'm not sure if you really want to combine all of them together if they're all provided. Instead, you can first determine a defaultValue inside the component, and then use that value for the default value of the input:

 <div id="root"></div><script src="https://unpkg.com/react@17.0.2/umd/react.development.js"></script><script src="https://unpkg.com/react-dom@17.0.2/umd/react-dom.development.js"></script><script src="https://unpkg.com/@babel/standalone@7.16.4/babel.min.js"></script> <script type="text/babel" data-type="module" data-presets="react"> function InputField ({nameValue, productValue, informationValue}) { /** * If all of the values are provided, they will all be combined in the string * but I don't think this is what you want */ // const defaultValue = `${nameValue? nameValue: ''} ${productValue? productValue: ''} ${informationValue? informationValue: ''}`; /** Instead, set it to the first one that has a truthy value, in order: */ const defaultValue = nameValue? nameValue: productValue? productValue: informationValue? informationValue: ''; return ( <div className='inputDiv'> <input type="text" placeholder="type info" defaultValue={defaultValue} /> </div> ); } function Example () { return ( <div> <InputField nameValue="name" /> <InputField productValue="product 6sd4f" /> <InputField informationValue="information 123" /> <InputField nameValue="first" productValue="second" informationValue="third" /> <InputField productValue="second" informationValue="third" /> <InputField nameValue="" productValue="second" informationValue="third" /> <InputField nameValue="" productValue="" informationValue="third" /> </div> ); } ReactDOM.render(<Example />, document.getElementById('root')); </script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM