Skip to content

Change the priorities of defaultChecked and checked #221

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions docs/examples/simple.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,33 @@ export default class SimpleDemo extends React.Component {
</p>
</div>

<div>
<p>
<label>
<Checkbox
defaultChecked
checked={undefined}
onChange={onChange}
disabled={this.state.disabled}
/>
&nbsp; defaultChecked rc-checkbox when checked value is undefined or null
</label>
&nbsp;&nbsp;
</p>
<p>
<label>
<input
type="checkbox"
defaultChecked
checked={undefined}
disabled={this.state.disabled}
/>
&nbsp; defaultChecked native checkbox when checked value is undefined or null
</label>
&nbsp;&nbsp;
</p>
</div>

<button type="button" onClick={this.toggle}>
toggle disabled
</button>
Expand Down
19 changes: 12 additions & 7 deletions src/index.jsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
// eslint-disable-next-line import/no-extraneous-dependencies
import React, { Component } from 'react';
import classNames from 'classnames';

Expand All @@ -21,15 +20,18 @@ class Checkbox extends Component {
constructor(props) {
super(props);

const checked = 'checked' in props ? props.checked : props.defaultChecked;
const checked =
'checked' in props && !(props.checked === undefined || props.checked === null)
? props.checked
: props.defaultChecked;

this.state = {
checked,
};
}

static getDerivedStateFromProps(props, state) {
if ('checked' in props) {
if ('checked' in props && !(props.checked === undefined || props.checked === null)) {
return {
...state,
checked: props.checked,
Expand All @@ -46,12 +48,15 @@ class Checkbox extends Component {
this.input.blur();
}

handleChange = e => {
const { disabled, onChange } = this.props;
handleChange = (e) => {
const { disabled, onChange, checked } = this.props;
if (disabled) {
return;
}
if (!('checked' in this.props)) {
if (
!('checked' in this.props) ||
('checked' in this.props && (checked === undefined || checked === null))
) {
this.setState({
checked: e.target.checked,
});
Expand All @@ -73,7 +78,7 @@ class Checkbox extends Component {
}
};

saveInput = node => {
saveInput = (node) => {
this.input = node;
};

Expand Down