繁体   English   中英

React 设置多个 defaultValue 来测试输入

[英]React set multiple defaultValue to test input

我想为每个不同的输入组件设置一个默认值,但它只适用于一个默认值。

页:

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

输入组件:

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

在此处输入图像描述

它工作正常吗? 你能附上你的问题吗?

如果它们都提供了,我不确定你是否真的想将它们全部组合在一起。 相反,您可以先在组件内部确定一个defaultValue ,然后将该值用作输入的默认值:

 <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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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