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

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

  />

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


12345678_0001
浏览 137回答 3
3回答

汪汪一只猫

你可以利用三元条件<Input&nbsp; &nbsp; type={type}&nbsp; &nbsp; name={input_key}&nbsp; &nbsp; id={input_key}&nbsp; &nbsp; {...(input_key === 'number'? min_max: {})}&nbsp; &nbsp; required={required}&nbsp; &nbsp; placeholder={placeholder}&nbsp; />

温温酱

只需有一个条件并使用传播语法。// sample proplet input_props = {&nbsp; type,&nbsp; name: input_key,&nbsp; id: input_key,}// condition to add min_max as prop.if (input_key === 'number') {&nbsp; input_props = {&nbsp; &nbsp; ...input_props,&nbsp; &nbsp; ...min_max&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // include min_max&nbsp;&nbsp; }}return (&nbsp; <Input&nbsp; &nbsp; {...input_props}&nbsp; &nbsp; &nbsp; &nbsp; // spread syntax to pass all input_props&nbsp; &nbsp; required={required}&nbsp; &nbsp; placeholder={placeholder}&nbsp; />)

慕雪6442864

没什么特别的class Example extends React.Component {&nbsp; constructor(props) {&nbsp; &nbsp; super(props);&nbsp; &nbsp; this.state = {};&nbsp; }&nbsp; render() {&nbsp; &nbsp; const min_max = {&nbsp; &nbsp; &nbsp; max : 10,&nbsp; &nbsp; &nbsp; min : 1&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; const j = false;&nbsp;&nbsp;&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp;<input type="number" { ...(j && min_max || {})} />&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; );&nbsp; }}ReactDOM.render(&nbsp; <Example />,&nbsp; 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>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript