Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
392 views
in Technique[技术] by (71.8m points)

javascript - 如何有条件地向React组件添加属性?(How to conditionally add attributes to React components?)

Is there a way to only add attributes to a React component if a certain condition is met?

(如果满足特定条件,是否有办法仅将属性添加到R??eact组件?)

I'm supposed to add required and readOnly attributes to form elements based on an ajax call after render, but I can't see how to solve this since readOnly="false" is not the same as omitting the attribute completely.

(我应该在渲染后基于ajax调用将required和readOnly属性添加到表单元素中,但是由于readOnly =“ false”与完全省略该属性不同,因此我看不到如何解决此问题。)

The example below should explain what I want, but wont work (Parse Error: Unexpected identifier).

(下面的示例应解释我想要的内容,但无法正常工作(解析错误:意外的标识符)。)

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" : ""} />
        );
    }
});
  ask by Remi Sture translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Apparently, for certain attributes, React is intelligent enough to omit the attribute if the value you pass to it is not truthy.

(显然,对于某些属性,如果您传递给它的值不真实,React足够聪明,可以忽略该属性。)

For example:

(例如:)

var InputComponent = React.createClass({
    render: function() {
        var required = true;
        var disabled = false;

        return (
            <input type="text" disabled={disabled} required={required} />
        );
    }
});

will result in:

(将导致:)

<input type="text" required>

Update: if anyone is curious as to how/why this happens, you can find details in ReactDOM's source code, specifically at lines 30 and 167 of the DOMProperty.js file.

(更新:如果有人对如何/为什么发生这种情况感到好奇,可以在ReactDOM的源代码中找到详细信息,特别是在DOMProperty.js文件的第30167行。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...