【发布时间】:2020-07-02 18:03:17
【问题描述】:
我有一个从 reactIcons npm 包https://www.npmjs.com/package/react-icons 输出的对象我正在使用import * as ReactIcons from 'react-icons/fa' 从其中一个文件夹中导入所有内容我正在使用sanity studio,我创建了一个文本输入,它采用搜索的值并运行在我从 reactIcons fa 文件夹中抓取的对象的值上运行包含的搜索功能,并记录匹配的值。现在我想获取这些值并使用useState() 更新一个反应组件,但是我收到以下错误Uncaught ReferenceError: setIcon is not defined 并且 SetIcon 是来自 useState 数组的设置器函数。到目前为止,这是我的代码
import React, { useState } from 'react';
import PropTypes from 'prop-types'
import FormField from 'part:@sanity/components/formfields/default'
import PatchEvent, {set, unset} from 'part:@sanity/form-builder/patch-event'
import * as ReactIcons from 'react-icons/fa'
console.log(ReactIcons);
const createPatchFrom = value => PatchEvent.from(value === '' ? unset() : set(String(value)))
const Example = value => {
const [icon, setIcon] = useState();
return (
<div>{icon}</div>
);
}
const search = value => {
console.log(value);
Object.keys(ReactIcons).map(go => {
if (go.toLowerCase().includes(value) === true){
console.log(go);
setIcon(go);
}
})
}
class IconPickerCustom extends React.Component{
static propTypes = {
value: PropTypes.string,
onChange: PropTypes.func.isRequired
};
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;
【问题讨论】:
-
为什么在使用类组件的时候还要使用hook????只需像往常一样设置和更新状态,不要使用钩子。 reactjs.org/docs/state-and-lifecycle.html
-
嗯,我不知道为什么。我对 react 不是很熟悉,我之前只玩过 hooks,所以在这里使用了它们。你能给我一个粗略的例子吗?
标签: javascript reactjs search sanity use-state