如何使用 react-bootstrap 表单中的“refs”获取输入值?

新手上路,请多包涵

我正在尝试创建一个以模态显示的表单。因此,当用户输入一个值时,该值将存储在本地存储中。这是一张图片,可以帮助您理解我的意思:

在此处输入图像描述 这是表单的代码:

 function FieldGroup({id, label, help, ...props}) {
    return (
        <ReactBootstrap.FormGroup controlId={id}>
            <ReactBootstrap.ControlLabel>{label}</ReactBootstrap.ControlLabel>
            <ReactBootstrap.FormControl {...props} />
            {help && <ReactBootstrap.HelpBlock>{help}</ReactBootstrap.HelpBlock>}
        </ReactBootstrap.FormGroup>
    );
}

const formInstance = (
    <form>
        <FieldGroup
            id="formControlsText"
            type="text"
            label="Text"
            placeholder="Recipe Name"
            inputRef={ref => { this.input = ref; }}
        />
        <ReactBootstrap.FormGroup controlId="formControlsTextarea">
            <ReactBootstrap.ControlLabel>Ingredients</ReactBootstrap.ControlLabel>
            <ReactBootstrap.FormControl componentClass="textarea" placeholder="Enter Ingredients" />
        </ReactBootstrap.FormGroup>
    </form>
);

正如我在引导 React 教程中所读到的,我应该添加

<FormControl inputRef={ref => { this.input = ref; }} /> 到 FormControl 道具。但是在添加它之后,当调用模态表单时出现错误:

` 在此处输入图像描述

原文由 Taras Yaremkiv 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 706
1 个回答

我刚刚做了这个问题。我的代码:

 <FormControl
    componentClass="input"
    placeholder="Enter recipe title"
    inputRef={(ref) => {this.input = ref}}
    defaultValue={title}/>
</FormGroup>

然后你可以在这样的处理程序中从 <FormControl> 获取值:

 console.log(this.input.value);

详细信息可以在我的仓库中找到: https ://github.com/kerf007/recipebook

原文由 Eugene Kulakov 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进