简体   繁体   English

如何在无状态组件中单击按钮获得输入值?

[英]how to get input value on button click in stateless component?

could you please tell me how to get input value on button click in stateless component .I want to pass input value in container component I tried like this .here is my code https://codesandbox.io/s/l9j42k5q49 您能告诉我如何在无状态组件中单击按钮时获取输入值吗?我想在container component传递输入值,我试图这样做。这是我的代码https://codesandbox.io/s/l9j42k5q49

import React from "react";
import PropTypes from "prop-types";

const TabbarComponent = props => {
  const onInputChange = event => {};
  return (
    <div>
      <input type="text" />
      <button onClick={() => props.addEventHandler()}>Add Items</button>
    </div>
  );
};

TabbarComponent.propTypes = {
  addEventHandler: PropTypes.func
};

export default TabbarComponent;

here I want input value in this function 在这里我想在这个函数中输入值

addButtonClickHandler(val) {
    alert("ddd");
    let names = this.state.names.slice();
    names.push(val);
    this.setState({
      names: names
    });
  }

val is input field value whatever user enter in input field valinput field value无论用户在输入字段中输入什么

You don't need to give onClick a fat arrow function. 您不需要给onClick箭头功能。 Just give it the reference to the addButtonClickHandler , like this: 只需为其提供对addButtonClickHandler的引用,如下所示:

<button onClick={props.addEventHandler}>Add Items</button>

You can do a fat arrow function if you want (not recommended), but in that case you need to pass the event too: 可以根据需要执行粗箭头功能(不建议这样做),但是在这种情况下,您也需要传递事件:

<button onClick={(e) => props.addEventHandler(e)}>Add Items</button>

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

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