如何在React中提交表单值?

问题描述 投票:-1回答:2

这是我的React组件

import React, { Component } from 'react';
import categories from './categories.json'
import './content.css'

export default class Content extends Component {
    constructor(props) {
        super(props)
        this.state = {
            searchText: '',
            categories
        }
    }

    render() {
        return(
            <div className="content">
            <form className="searchform" onSubmit={this.search}>
                <input type="text" name="keyword" id="searchbox" placeholder="Search String"></input>
                <select name="categories" id="searchcategories">
                <option defaultValue="" defaultChecked>Select a category</option>
                {this.state.categories.map(x => 
                    <option key={x.value} value={x.value}>{x.name}</option>
                )}</select>
                <input type="submit" value ="Search" id="searchsubmit" />
            </form>
            </div>
        )
    }

    search(e) {
        console.log(e.target)
        e.preventDefault();
    }
}

单击提交按钮,我的函数search会被调用。但是,如何获取提交的值?

e.target给了我整个表格DOM HTML e.target.valueundefined

forms reactjs
2个回答
4
投票

在React中,您有两种表单组件选项:

受控组件(https://reactjs.org/docs/forms.html#controlled-components)的值通过将其值prop设置为状态变量而与组件状态相关联。在这种情况下,您可以使用组件的this.state来检查它们的值。

不受控制的组件(https://reactjs.org/docs/uncontrolled-components.html)在实例化时可以附加到其父组件的引用...通常像这样的ref={(input) => this.input = input}。调用函数search时,可以检查值的引用,即this.input.value


0
投票

您需要使用状态变量。例如,只要文本发生变化,就会将this.state.searchText与元素同步。然后定义一个回调机制,如 -

onSubmit={()=>{
console.log('My searchBox's latest value is : ',this.state.searchText);
}}

请记住,在React中我们遵循单向流程。因此,我们总是从道具或状态中获取数据,而不需要处理DOM遍历。

© www.soinside.com 2019 - 2024. All rights reserved.