React中如何通过Props设置组件状态?自定义React Select组件问题
问题原因
你用useState(disable)初始化状态时,这个初始值只会在组件第一次挂载时被读取一次。后续父组件传入的disable prop发生变化时,isDisabled状态不会自动跟着更新,所以直接传disable={true}不生效;而defaultProps是组件首次渲染时的默认prop值,会被作为useState的初始值,所以能生效。
解决方案
根据你的需求选择下面其中一种:
方案1:不需要内部修改禁用状态,直接用prop
如果你的组件不需要在内部修改isDisabled(只通过父组件传prop控制),完全没必要用state,直接把disable prop传给React Select的isDisabled属性:
import React from "react"; import Select from 'react-select'; import './select.scss'; import PropTypes from 'prop-types'; const MySelect = ({ options, disable }) => { return ( <Select options={options} isDisabled={disable} /> ); }; MySelect.propTypes = { disable: PropTypes.bool, options: PropTypes.array, }; MySelect.defaultProps = { disable: false, options: [ { value: 'chocolate', label: 'Chocolate' }, { value: 'strawberry', label: 'Strawberry' }, { value: 'vanilla', label: 'Vanilla' } ] }; export default MySelect;
方案2:需要内部修改禁用状态,同时响应prop变化
如果你的组件需要在内部通过setIsDisabled修改禁用状态,同时还要响应父组件传入的disable prop变化,就用useEffect监听disable prop,同步更新state:
import React, { useState, useEffect } from "react"; import Select from 'react-select'; import './select.scss'; import PropTypes from 'prop-types'; const MySelect = ({ options, disable }) => { const [isDisabled, setIsDisabled] = useState(disable); // 当disable prop变化时,更新内部状态 useEffect(() => { setIsDisabled(disable); }, [disable]); return ( <Select options={options} isDisabled={isDisabled} /> ); }; MySelect.propTypes = { disable: PropTypes.bool, options: PropTypes.array, }; MySelect.defaultProps = { disable: false, options: [ { value: 'chocolate', label: 'Chocolate' }, { value: 'strawberry', label: 'Strawberry' }, { value: 'vanilla', label: 'Vanilla' } ] }; export default MySelect;
内容的提问来源于stack exchange,提问作者MeltingDog
相关产品推荐
相关产品推荐

