首页 文章

如何有条件地向React组件添加属性?

提问于
浏览
305

有没有办法只在满足某个条件时才向React组件添加属性?

我应该在渲染之后添加必需和readOnly属性以基于ajax调用来形成元素,但我看不出如何解决这个问题,因为readOnly =“false”与完全省略属性不同 .

下面的例子应该解释我想要什么,但不会工作(解析错误:意外的标识符) .

var React = require('React');

var MyOwnInput = React.createClass({
    render: function () {
        return (
            <div>
                <input type="text" onChange={this.changeValue} value={this.getValue()} name={this.props.name}/>
            </div>
        );
    }
});

module.exports = React.createClass({
    getInitialState: function () {
        return {
            isRequired: false
        }
    },
    componentDidMount: function () {
        this.setState({
            isRequired: true
        });
    },
    render: function () {
        var isRequired = this.state.isRequired;

        return (
            <MyOwnInput name="test" {isRequired ? "required" : ""} />
        );
    }
});

11 回答

  • 3

    考虑到这篇文章https://facebook.github.io/react/tips/if-else-in-JSX.html,您可以通过这种方式解决问题

    if (isRequired) {
      return (
        <MyOwnInput name="test" required='required' />
      );
    }
    return (
        <MyOwnInput name="test" />
    );
    
  • 6

    您可以使用相同的快捷方式,用于添加/删除(部分)组件( {isVisible && <SomeComponent />} ) .

    class MyComponent extends React.Component {
      render() {
        return (
          <div someAttribute={someCondition && someValue} />
        );
      }
    }
    
  • 260

    这应该有效,因为您的状态将在ajax调用之后发生更改,并且父组件将重新呈现 .

    render : function () {
        var item;
        if (this.state.isRequired) {
            item = <MyOwnInput attribute={'whatever'} />
        } else {
            item = <MyOwnInput />
        }
        return (
            <div>
                {item}
            </div>    
        );
    }
    
  • 0

    显然,对于某些属性,React足够智能,如果传递给它的值不是真的,则省略该属性 . 例如:

    var InputComponent = React.createClass({
        render: function() {
            var required = true;
            var disabled = false;
    
            return (
                <input type="text" disabled={disabled} required={required} />
            );
        }
    });
    

    将导致:

    <input type="text" required data-reactid=".0.0">
    
  • 161

    迟到了 .

    让我们说如果条件为真,我们想要添加一个自定义属性(使用aria- *或data- *):

    {...this.props.isTrue && {'aria-name' : 'something here'}}
    

    假设我们想要在条件为真时添加样式属性:

    {...this.props.isTrue && {style : {color: 'red'}}}
    
  • 4

    只是抛出另一个选项,但 @juandemarco's 答案通常是正确的 .

    根据自己的喜好构建对象:

    var inputProps = {
      value: 'foo',
      onChange: this.handleChange
    };
    
    if (condition) inputProps.disabled = true;
    

    使用传播渲染,也可以选择传递其他道具 .

    <input 
        value="this is overridden by inputProps" 
        {...inputProps} 
        onChange={overridesInputProps}
     />
    
  • 48

    这是我做的一种方式 .

    with Conditional

    <Label
        {...{
          text: label,
          type,
          ...(tooltip && { tooltip }),
          isRequired: required
        }}
      />
    

    我仍然喜欢使用常规方式传递道具,因为在没有任何条件的情况下它更具可读性(在我看来) .

    with No conditional

    <Label text={label} type={type} tooltip={tooltip} isRequired={required} />
    
  • 8

    在React中,您可以有条件地呈现组件,但也可以使用其属性,如props,className,id等 .

    在React中,使用“三元运算符”是非常好的做法,它可以帮助您有条件地渲染组件 .

    示例还显示了如何有条件地呈现Component及其样式属性

    这是一个简单的例子:

    class App extends React.Component {
      state = {
        isTrue: true
      };
    
      render() {
        return (
          <div>
            {this.state.isTrue ? (
              <button style={{ color: this.state.isTrue ? "red" : "blue" }}>
                I am rendered if TRUE
              </button>
            ) : (
              <button>I am rendered if FALSE</button>
            )}
          </div>
        );
      }
    }
    
    ReactDOM.render(<App />, document.getElementById("root"));
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
    
    <div id="root"></div>
    
  • 0

    以下是通过React-Bootstrap使用BootstrapButton的示例 .

    var condition = true;
    
    return (
      <Button {...(condition ? {bsStyle: 'success'} : {})} />
    );
    

    根据条件,将返回 {bsStyle: 'success'}{} . 然后,扩展运算符将返回对象的属性扩展到 Button 组件 . 在虚假的情况下,由于返回的对象上不存在任何属性,因此不会将任何内容传递给组件 .


    基于@Andy Polhill的评论的替代方式如下:

    var condition = true;
    
    return (
      <Button bsStyle={condition ? 'success' : undefined} />
    );
    

    唯一的小区别是,在第二个示例中,内部组件 <Button/>props 对象将具有值 bsStyle ,其值为 undefined .

  • 311

    如果你使用es6,你可以这样写 .

    // first, create a wrap object.
    const wrap = {
        [variableName]: true
    }
    // then, use it
    <SomeComponent {...{wrap}} />
    
  • 12

    迟到了 . 这是另一种选择 .

    var condition = true;
    
    var props = {
      value: 'foo',
      ...( condition && { disabled: true } )
    };
    
    var component = <div { ...props } />;
    

    或其内联版本

    var condition = true;
    
    var component = (
      <div
        value="foo"
        { ...( condition && { disabled: true } ) } />
    );
    

相关问题