繁体   English   中英

使用 Hooks 在 React 中重用状态

[英]Reusing state in React with Hooks

我看到自己使用如下声明:

const [state, setState] = React.useState({value: ''});
    
return <InputComponent {...properties} value={state.value} onChange={(event) => setState({value: event.target.value || event.target.checked}

每当一个组件需要状态时,我都必须重写它,而且感觉根本无法重用。 我寻找渲染道具和 HOC,但无法重用状态。

我尝试创建:

const StatefulInput = (InputComponent) => {

  const [state, setState] = React.useState({value: ''});

  return <InputComponent value={state.value} onChange={(event) => setState({value: event.target.value || event.target.checked />
}

但是我无法重用,我遇到了“无效的钩子”、“呈现接收到的对象而不是其他东西”错误和其他一些错误。

我该怎么做? 可以重用这个钩子吗?

为了避免样板,您可以编写一个自定义钩子来保存状态,返回一个值和一个可以传递给子组件的处理程序:

 const InputComponent = ({ value, onChange }) => <input {...{value, onChange}} />; const useInputValue = (initialValue) => { const [value, setValue] = React.useState(initialValue); return [ value, event => setValue(event.target.value || event.target.checked) ]; }; const App = () => { const [inputValue, inputHandler] = useInputValue(''); return <InputComponent value={inputValue} onChange={inputHandler} /> }; ReactDOM.render(<App />, document.querySelector('.react'));
 <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> <div class="react"></div>

或者,让自定义钩子返回一个可以传播到子组件中的对象:

 const InputComponent = ({ value, onChange }) => <input {...{value, onChange}} />; const useInputValue = (initialValue) => { const [value, setValue] = React.useState(initialValue); return { value, onChange: event => setValue(event.target.value || event.target.checked) }; }; const App = () => { const inputProps = useInputValue(''); return <InputComponent {...inputProps} /> }; ReactDOM.render(<App />, document.querySelector('.react'));
 <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> <div class="react"></div>

还要注意, useState的有状态值useState是一个对象 - 在这里,由于您需要存储的只是一个字符串(当前值),您可以让状态只是那个 string ,而不是将字符串包装在一个不必要的对象。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM