reactjs - 从 javascript/react 更新 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
prop 可用于在初始渲染时设置输入值,但组件故意不提供公共 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}
/>
);
推荐阅读
- excel - 查找、替换和计算多个值
- javascript - 每个页面都显示相同的内容?
- flutter - 在颤动的文本旁边显示图像
- node.js - 个人资料页面未经授权 (GET 401)
- python-3.x - KeyError:在使用 Naive 和 SVM 进行情感分析时字典中的“无关”
- c# - 从 .net 2.0 项目打开 .net 4.5 项目的 windows 形式时出现运行时错误
- codeigniter - 在控制器 Codigniter 2.2.6 中加载模型时出现问题
- javascript - 为什么我的手风琴在单击时不显示子选项卡?
- python - 遍历字典前辈
- c - 将头文件与共享库链接