繁体   English   中英

从无状态组件获取输入值

[英]Get Input Value From Stateless Component

CONTEXT

我试图从另一个无状态组件中的无状态组件获取输入字段的值,然后使用它来调用方法。 我正在为我的UI组件使用rebass,并在Meteor + Mantra中执行此操作。

我知道如果我使用<input> HTML字段而不是另一个无状态组件,我可以通过使用ref来实现。

问题

我当前的代码会使preventDefault未定义,并且在删除时,console.log会在每次输入更改时打印出来,而不是在提交时打印出来。 我相信我的状态适用于整个Dashboard组件,而不是无状态Rebass <Input/> ,但我不知道如何更改它。

import React from 'react';
import {PageHeader, Container, Input,Button} from 'rebass';

class Dashboard extends React.Component {
  constructor(props) {
    super(props);

    this.state = { websiteUrl: ''};
    this.onInputChange = this.onInputChange.bind(this);
    this.onFormSubmit = this.onFormSubmit.bind(this);
  }

  onInputChange(event) {
    this.setState({websiteUrl:event.target.value});    
  }

  onFormSubmit() {
    event.preventDefault;
    const {create} = this.props;
    const {websiteUrl} = this.state.websiteUrl;
    console.log(this.state.websiteUrl);
    create(websiteUrl);
  }    

  render() {
    const { error } = this.props;

    return (
      <div>

      <PageHeader
        description="Dashboard Page"
        heading="Dashboard"
      />

      <Container>
      <form>
            <Input
              value={this.state.websiteUrl}
              type="text"
              buttonLabel="Add Website"
              label="Website"
              name="add_website"
              onChange={this.onInputChange}    
            />

            <Button
              backgroundColor="primary"
              color="white"
              inverted={true}
              rounded={true}
              onClick={this.onFormSubmit()}
            > Add Website </Button>    
        </form>    
      </Container>
      </div>
    );
  }    
}

export default Dashboard;

您应该将event传递给onFormSubmit函数:

    <Button
      backgroundColor="primary"
      color="white"
      inverted={true}
      rounded={true}
      onClick={(event) => this.onFormSubmit(event)}
      ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM