繁体   English   中英

如何有条件地在反应组件上添加道具?

[英]how to conditionally add props on a react component?

我想有条件地在输入类型上添加道具,我想检查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}
  />

我如何通过使用这样的传播使其工作?

您可以利用三元条件

<Input
    type={type}
    name={input_key}
    id={input_key}
    {...(input_key === 'number'? min_max: {})}
    required={required}
    placeholder={placeholder}
  />

只需有一个条件并使用扩展语法。

// 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}
  />
)

没什么特别的

 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>

我认为如果你的输入有 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}
/>

希望能帮助到你

你可以把它做成 function

  const getNumberInputProps = (inputKey, otherProps) => {
    if (inputKey === "number")
        return otherProps
    return {}
}

然后你可以调用它并像这样传播 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.

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