Làm thế nào để thêm các attributes vào các React components một cách có điều kiện?

{{FormatNumbertoThousand(model.total_like)}} lượt thích
263 lượt xem
Reactjs senior

Vấn đề:

Có cách nào để chỉ thêm các attributes vào một React component nếu một điều kiện nhất định được đáp ứng không?

Giải pháp:

Đối với một số attributes nhất định, React đủ thông minh để bỏ qua attribute đó nếu giá trị bạn truyền cho nó không là true. Ví dụ:

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

sẽ cho kết quả:

<input type="text" required>

Một cách tiếp cận khả thi khác là:

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