如何在 React 中使用 <button> 和 <input> 从用户那里获取输入?

How do I get input from user by using <button> and <input> in React?

我想使用 <input><button> 创建一个表单,如下所示:

当我按下“立即发送”按钮时,我不确定如何将从文本输入字段获得的值传递给前端的几个函数。如何在不使用表单的情况下制作 <form onSubmit={}>,而只使用输入字段和按钮?

这是我迄今为止尝试过的方法,但它不起作用,我不确定如何获取输入值并将其传递给这样的函数 this.articleOnSubmit(*user input*)。还有我合并 onChange={this.articleOnChange} 的方式是否正确?这是我的代码:

const Input = ({ placeholder, name, type, value }) => (
    <input
      placeholder={placeholder}
      type={type}
      step="0.0001"
      value={value}
      name={value}
    />
);

class Publish extends Component {
  constructor(props) {
    super(props);
    this.state = {
      articleTitle: '',
    };
  }
 
  articleOnChange = (event) => {
    let title = event.target.value;
    this.setState({ articleTitle: title.toLowerCase() });
  }

  articleOnSubmit = (event) => {
    if (this.state.articleTitle) {
    console.log(this.state.articleTitle);
    this.hash(this.state.articleTitle)
      .then(hex => {console.log(hex); return hex;})
      .then(hex => this.addArticleHash(hex));
  
    event.preventDefault();
 }
  
  return (
   <Input placeholder="Article Name" name="article" type="text" onChange={this.articleOnChange} />
     <div/>
     {false
     ? (<Loader />)
     : (
     <button
     type="submit"
     onClick={this.articleOnSubmit(Input.name)}
     >
     Send now
     </button>
  )}
  </div>
 );
  
}

要使其正常工作,您必须在此处解决 2 个问题:

  1. 因为Input是一个组件,你必须在它的道具中得到你传递给它的onChange道具,否则它不会工作。
const Input = ({ placeholder, name, type, value, onChange }) => (
  <input
    onChange={onChange}
    placeholder={placeholder}
    type={type}
    step="0.0001"
    value={value}
    name={value}
  />
);
  1. React onClick 应该是一个函数。不是电话。一个功能。你在这里做的是 onClick={this.articleOnSubmit(Input.name)} - 这是一个调用。

解决办法是改成函数() => this.articleOnSubmit(Input.name)