React JSX中的不确定复选框

ᆼᆺᆼ*_*ᆼᆺᆼ 12 javascript reactjs react-jsx

如何在JSX中呈现不确定的复选框?

这是我尝试过的:

render() {
  return <input type="checkbox" 
                checked={this.props.state === "checked"} 
                indeterminate={this.props.state === "indeterminate"} />
}
Run Code Online (Sandbox Code Playgroud)

但是,indeterminate不是属性HTMLElement,而是属性.如何从React/JSX设置属性?

Mic*_*ley 11

我可能会创建一个复合组件,它封装了必要的钩子来设置或取消设置复选框的indeterminate属性.看起来你正在使用ES2015语法,所以我将在这里使用其中的一些功能.

class IndeterminateCheckbox extends React.Component {
  componentDidMount() {
    if (this.props.indeterminate === true) {
      this._setIndeterminate(true);
    }
  }

  componentDidUpdate(previousProps) {
    if (previousProps.indeterminate !== this.props.indeterminate) {
      this._setIndeterminate(this.props.indeterminate);
    }
  }

  _setIndeterminate(indeterminate) {
    const node = React.findDOMNode(this);
    node.indeterminate = indeterminate;
  }

  render() {
    const { indeterminate, type, ...props } = this.props;
    return <input type="checkbox" {...props} />;
  }
}

// elsewhere

render() {
  return <IndeterminateCheckbox
           checked={this.props.state === "checked"} 
           indeterminate={this.props.state === "indeterminate"} />
}
Run Code Online (Sandbox Code Playgroud)

工作示例:https://jsbin.com/hudemu/edit?js,output

  • 请注意,从 0.14 开始不推荐使用 `React.findDOMNode`。使用来自 `react-dom` 包的 `ReactDOM.findDOMNode` 代替。 (2认同)

man*_*nji 9

您可以使用componentDidMount步骤(在初始渲染后调用)来设置该属性:

componentDidMount() {
    React.findDOMNode(this).indeterminate = this.props.state === "indeterminate";
}
Run Code Online (Sandbox Code Playgroud)

如果您希望使用后续渲染更新该属性,请同样执行相同的操作componentDidUpdate.


Kév*_*ier 9

也可以直接使用 ref 函数:

ReactDOM.render(
  <label>
    <input
      type="checkbox"
      ref={input => {
        if (input) {
          input.indeterminate = true;
        }
      }}
    />
    {' '}
    Un test
  </label>,
  document.getElementById('root')
);
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)


kas*_*ter 5

我建议创建一个简单的组件(从 coffeescript 移植的代码,所以请注意,可能有一些简单的错别字):

const React = require('react');

module.exports = class IndeterminateCheckbox extends React.Component {
    componentDidMount() {
        this.refs.box.indeterminate = this.props.indeterminate;
    }

    componentDidUpdate(prevProps, prevState) {
        if(prevProps.indeterminate !== this.props.indeterminate) {
            this.refs.box.indeterminate = this.props.indeterminate;
        }
    }

    render() {
        return <input {...this.props} ref="box" type="checkbox"/>;
    }

}
Run Code Online (Sandbox Code Playgroud)

现在你有一个简单的组件,它的行为与复选框完全一样,支持indeterminateprop。请注意,这里有很大的改进空间,即为某些道具设置 propTypes 和适当的默认值,当然componentShouldUpdate,仅在需要时才执行某些操作。