从 javascript/react 更新 react bootstrap typeahead 中的输入文本

问题描述

您好,我正在尝试创建一个 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 .

解决方法

注意:强烈建议不要使用这两种解决方法。

  1. 您可以通过在每次新安装时使用新的默认输入值卸载和重新安装组件(例如:通过更改密钥)来利用 defaultInputValue。这是非常严厉的,可能会导致性能问题或错误。
const [key,setKey] = useState(0);
const [value,setValue] = useState('');

return (
  <Typeahead
    ...
    defaultInputValue={value}
    key={key}
    onBlur={(e) => {
      setValue('some value');
      setKey(key + 1);
    }}
  />
);
  1. 您可以使用 ref 访问组件实例并使用 setState 方法更新组件状态的 text 键。这显然是不推荐的,因为 setState 是私有的,非常脆弱,随时可能损坏
const ref = useRef(null);

return (
  <Typeahead
    ...
    onBlur={() => {
      ref.current.setState({
        text: 'some value',});
    }}
    ref={ref}
  />
);

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...