[英]how to conditionally add props on a react component?
I want to conditionally add props on an input type, I want to check if input_key
is a number and if it is, I want to add min_max
props, cause I don't want it added if it's of any type我想有条件地在输入类型上添加道具,我想检查
input_key
是否是数字,如果是,我想添加min_max
道具,因为如果它是任何类型,我不希望添加它
const min_max = {
min: 0,
max: 100
};
<Input
type={type}
name={input_key}
id={input_key}
{input_key === 'number' && ...min_max}
required={required}
placeholder={placeholder}
/>
how do I make it work by using spread like that?我如何通过使用这样的传播使其工作?
You can make use of ternary condition您可以利用三元条件
<Input
type={type}
name={input_key}
id={input_key}
{...(input_key === 'number'? min_max: {})}
required={required}
placeholder={placeholder}
/>
Simply have a condition and use spread syntax.只需有一个条件并使用扩展语法。
// sample prop
let input_props = {
type,
name: input_key,
id: input_key,
}
// condition to add min_max as prop.
if (input_key === 'number') {
input_props = {
...input_props,
...min_max // include min_max
}
}
return (
<Input
{...input_props} // spread syntax to pass all input_props
required={required}
placeholder={placeholder}
/>
)
Nothing special没什么特别的
class Example extends React.Component { constructor(props) { super(props); this.state = {}; } render() { const min_max = { max: 10, min: 1 } const j = false; return ( <div> <input type="number" {...(j && min_max || {})} /> </div> ); } } ReactDOM.render( <Example />, document.getElementById('root') );
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="root"></div>
I think you can do this if you have min and max prop to your input as我认为如果你的输入有 min 和 max 属性,你可以这样做
<Input
type={type}
name={input_key}
id={input_key}
max={inputKey === 'number' ? min_max.max : ''}
min={inputKey === 'number' ? min_max.min : ''}
required={required}
placeholder={placeholder}
/>
Hope it helps希望能帮助到你
You can make it into a function你可以把它做成 function
const getNumberInputProps = (inputKey, otherProps) => {
if (inputKey === "number")
return otherProps
return {}
}
then you can call it and spread the output like this然后你可以调用它并像这样传播 output
<Input
type={type}
name={input_key}
id={input_key}
{...getNumberInputProps(input_key, min_max)}
required={required}
placeholder={placeholder}
/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.