React Component Design - State Initializers
- 發佈時間
延續Toggle
的例子,有些時候我們希望將元件的 state 還原回初始 state,與其用 setState 將on
的狀態設成 false,到不如利用下列的技巧
已複製!class Toggle extends React.Component { static defaultProps = { initialOn: false, onReset: () => {}, }; initialState = { on: this.props.initialOn }; state = this.initialState; reset = () => this.setState(this.initialState, () => this.props.onReset(this.state.on)); getStateAndHelpers() { return { on: this.state.on, toggle: this.toggle, reset: this.reset, getTogglerProps: this.getTogglerProps, }; } // same as before } function Usage({ initialOn = false, onToggle = (...args) => console.log('onToggle', ...args), onReset = (...args) => console.log('onReset', ...args), }) { return ( <Toggle initialOn={initialOn} onToggle={onToggle} onReset={onReset}> {({ getTogglerProps, on, reset }) => ( <div> <Switch {...getTogglerProps({ on })} /> <hr /> <button onClick={() => reset()}>Reset</button> </div> )} </Toggle> ); }