1 回答

TA贡献1883条经验 获得超3个赞
React 有两类组件,类组件和函数组件(以前称为无状态组件)。当您意识到需要在函数组件中使用状态并且不想将其转换为类组件时,会在函数组件中使用钩子。
useState() Hook 允许我们在函数组件中添加状态。
类组件
//initialize state
constructor(props) {
super(props);
this.state = {foo: bar};
}
//set state
this.setState({foo: baz});
//read state
this.state.foo;
函数组件
(带有 useState() Hook)
//initialize state
const [icon, setIcon] = useState("myInitialValue");
//set state
setIcon("myNewValue");
//read state
{icon}
话虽如此,你已经有了一个类组件,所以这里不需要使用钩子。
class IconPickerCustom extends React.Component{
constructor(props) {
super(props);
this.state = { icon: "nothing" };
}
static propTypes = {
value: PropTypes.string,
onChange: PropTypes.func.isRequired
};
const createPatchFrom = value => PatchEvent.from(value === '' ? unset() : set(String(value)));
const search = value => {
Object.keys(ReactIcons).map(go =>
({ go.toLowerCase().includes(value) ?
this.setState({icon:go}) : null;})
}
render = () =>{
const {type, value, onChange} = this.props
return (
<>
<FormField label={type.title} description={type.description}>
<input
type="text"
value={value === undefined ? '' : value}
onChange={event => onChange(createPatchFrom(event.target.value))}
ref={element => this._inputElement = element}
/>
</FormField>
<input
type="text"
onChange={event => search(event.target.value)}
/>
{Object.values(ReactIcons).map(X =>{
return (
<>
<X/>
</>
);
})}
{console.log(ReactIcons.Fa500Px)}
<ReactIcons.Fa500Px/>
<Example/>
</>
)
}
}
export default IconPickerCustom;
你会想要一些类似的东西。如果您有任何问题,请告诉我。
添加回答
举报