Languages
[Edit]
PL

React - trójstanowe pole wyboru (checkbox)

6 points
Created by:
Niac
478

W tym krótkim artykule chcielibyśmy pokazać, jak utworzyć trójstanowe pole wyboru w Reakcie - trzy-stanowy przycisk checkbox.

W tym celu tworzony jest element input typu checkbox, który używa wbudowanej własności indeterminate. Trójstanowe pole wyboru rozumiemy jako pole, które jest w stanie uzyskać trzy stany: true, false i null. null jest wartościę nieustawioną.

Trójstanowe pole wyboru w React
Trójstanowe pole wyboru w React

Praktyczny przykład:

// ONLINE-RUNNER:browser;

// Uwaga: Odkomentuj poniższe linijki podczas pracy z kompilatorem JSX:
// import React from 'react';
// import ReactDOM from 'react-dom';

const updateInput = (ref, checked) => {
  	const input = ref.current;
    if (input) {
        input.checked = checked;
        input.indeterminate = checked == null;
    }
};

const ThreeStateCheckbox = ({name, checked, onChange}) => {
    const inputRef = React.useRef(null);
    const checkedRef = React.useRef(checked);
    React.useEffect(() => {
        checkedRef.current = checked;
        updateInput(inputRef, checked);
    }, [checked]);
    const handleClick = () => {
        switch (checkedRef.current) {
            case true:
                checkedRef.current = false;
                break;
            case false:
                checkedRef.current = null;
                break;
            default: // null
                checkedRef.current = true;
                break;
        }
        updateInput(inputRef, checkedRef.current);
        if (onChange) {
          	onChange(checkedRef.current);
        }
    };
    return (
      <input ref={inputRef} type="checkbox" name={name} onClick={handleClick} />
    );
};

const App = () => {
    const [checked, setChecked] = React.useState(null);
    const handleChange = (checked) => {
      	console.log(`checked: ${checked}`);
    };
    return (
      <ThreeStateCheckbox checked={checked} onChange={handleChange} />
    );
};

const root = document.querySelector('#root');
ReactDOM.render(<App />, root );

Alternative titles

  1. React - trzystanowe pole wyboru (checkbox)
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

ReactJS (PL)

React - trójstanowe pole wyboru (checkbox)
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join