问题描述
您好,我正在尝试创建一个 react bootstrap typeahead,我可以在其中从 javascript 更新我的输入文本。它适用于控制台,但不适用于代码。
let typeaheadInput = document.getElementById('exTypeahead')
typeaheadInput.value = typeaheadInput.value + 'some text'
有没有其他方法可以在预先输入的输入框中插入文本
import React from 'react';
import { Typeahead } from "react-bootstrap-typeahead";
const data = [
{id: 1,fullName: 'John'},{id: 2,fullName: 'Peter'},{id: 3,fullName: 'Blaszczykowski'},{id: 4,fullName: 'lewandowski'},]
class TypeaheadComp extends React.Component {
constructor(props){
super(props)
this.state = {
selectedList: []
}
}
render() {
return <Typeahead
id="basic-example"
onChange={(selected) => {
let temp = [];
selected.map(x => {
temp.push(x);
});
this.setState({selectedList: temp})
}}
options={data}
placeholder="Select name or create full name"
selected={this.state.selectedList}
labelKey="fullName"
multiple
allowNew
newSelectionPrefix="Enter full name: "
inputProps={{id:'exTypeahead'}}
/>;
}
}
export default TypeaheadComp
解决方法
defaultInputValue
属性可用于在初始渲染上设置输入值,但组件 intentionally does not provide 是用于以受控方式设置输入值的公共 API .
解决方法
注意:强烈建议不要使用这两种解决方法。
- 您可以通过在每次新安装时使用新的默认输入值卸载和重新安装组件(例如:通过更改密钥)来利用
defaultInputValue
。这是非常严厉的,可能会导致性能问题或错误。
const [key,setKey] = useState(0);
const [value,setValue] = useState('');
return (
<Typeahead
...
defaultInputValue={value}
key={key}
onBlur={(e) => {
setValue('some value');
setKey(key + 1);
}}
/>
);
- 您可以使用 ref 访问组件实例并使用
setState
方法更新组件状态的text
键。这显然是不推荐的,因为setState
是私有的,非常脆弱,随时可能损坏
const ref = useRef(null);
return (
<Typeahead
...
onBlur={() => {
ref.current.setState({
text: 'some value',});
}}
ref={ref}
/>
);