Indeterminate checkbox in React JSX

前端 未结 7 1623
旧时难觅i
旧时难觅i 2021-01-01 17:00

How do I render an indeterminate checkbox via JSX?

Here\'s what I\'ve tried:

function ICB({what}) {
  return 

        
7条回答
  •  甜味超标
    2021-01-01 17:30

    I'd suggest creating a simple component (code ported from coffeescript so mind you, might have some simple typos):

    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 ;
        }
    
    }
    

    Now you have a simple component that behaves exactly like a checkbox, that supports the indeterminate prop. Note there's plenty of room for improvements here, namely setting propTypes and proper defaults for some props, and of course implementing componentShouldUpdate to only do something when needed.

提交回复
热议问题