首页 > 解决方案 > 从 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

标签: reactjsreact-bootstrap-typeahead

解决方案


defaultInputValueprop 可用于在初始渲染时设置输入值,组件故意不提供公共 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}
  />
);

推荐阅读