【问题标题】:Form Submit React and Rails表单提交 React 和 Rails
【发布时间】:2020-11-19 21:33:41
【问题描述】:

我是 React 的超级新手。基本上我现在有两个组件。我的 SearchInput-Component 是一个用于城市的选择,它进行实时搜索。它工作得非常好,看起来像这样:

我将此组件添加到我的 CityForm 组件中,这是一个我需要提交的搜索表单。在这里我被困住了。现在我刚刚检查了提交是否适用于简单的警报。

class CityForm extends React.Component {

  handleSubmit(event) {
    alert('Try tomorrow')
  }
 
  render() {
    return (
      <form onSubmit={this.handleSubmit}>
                <SearchInput placeholder="search city" style={{ width: 200 }} />
      </form>

    );
  }
}


ReactDOM.render(
    <CityForm />,   
    document.getElementById('react-form')
);

我在想提交应该是一种发布请求。现在,当我提交时,我的 URL 不会改变,我需要对某种 URL 进行发布请求。 post 的 url 将是 smth。喜欢

filter?[city_id_eq]=02000000&commit=Search

我想对了吗?而且,我需要从 Select 中获取 city_id,它在提交之前基本上总是有一个值。应该将handleSubmit的状态值设置为select的值,我该怎么做?

也许它是相关的,这就是我在 SearchInput 中呈现的内容

render() {
    const options = this.state.data.map(d => <Option key={d.value}>{d.text}</Option>);
    return (
      <Select
        showSearch
        value={this.state.value}
        placeholder={this.props.placeholder}
        style={this.props.style}
        defaultActiveFirstOption={false}
        showArrow={false}
        filterOption={false}
        onSearch={this.handleSearch}
        onChange={this.handleChange}
        notFoundContent={null}
      >
        {options}
      </Select>
    );

【问题讨论】:

  • 我不确定你想要达到什么目的?如果你想做一个 GET 请求,那么可以使用 fetchAPI 或 axios。如果您的问题是如何从CityForm 中的SearchInput 获取数据,那么我建议您阅读this

标签: ruby-on-rails reactjs react-native


【解决方案1】:

首先,您在CityForm 组件中创建一个新的value 状态,然后从SearchInput 组件中删除value 状态。换句话说,提升状态。之后,您可以通过回调函数更新SearchInput 中的CityFormvalue 状态。类似的东西: https://symfonycasts.com/screencast/reactjs/callback-props 然后,您将在 CityForm 组件的状态下获得可用的城市 ID。

其次,使用 use,例如,Axios 来发出表单 post 请求。 https://www.digitalocean.com/community/tutorials/react-axios-react#step-3-%E2%80%94-making-a-post-request

附:一旦你对 React 组件有了一点熟悉,就研究一下 React 钩子。 ;)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-15
    • 1970-01-01
    • 1970-01-01
    • 2014-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多