简体   繁体   English

如何从React组件访问event.target.value

[英]How to access event.target.value from React component

I can't access the value of event.target.value from a React child Component, but I can from an HTML tag. 我无法从React子组件访问event.target.value的值,但可以从HTML标记访问。

In the example given: it doesn't work for the Button tag (React Component) but works for the button tag (html tag). 在给出的示例中:它不适用于Button标签(React Component),但适用于Button标签(html标签)。


import React from "react";
import Button from "./components/Button";

class Calculator extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            topText: "0"
        }
        this.handleClick = this.handleClick.bind(this);

    }

        handleClick(event) {
            this.setState({ topText: event.target.value })
        }

    render() {
        return (
            <div>
                <div>{this.state.topText}</div>
                <Button value='1' onClick={this.handleClick}/>
                <button value="2" onClick={this.handleClick}>2</button>
            </div>
        )
}
}

export default Calculator

Do you have onClick handled inside your button component ? 您在按钮组件内部处理过onClick吗? If no thats the reason. 如果没有,那就是原因。

As you are passing onClick props on Button component, So inside Button component. 在按钮组件上传递onClick道具时,在按钮组件内传递。

<button  onClick={onClick}/>

At the end onClick should be on HTML component only inside Button. 最后,onClick应该仅在Button内部位于HTML组件上。

You cannot have onClick on components. 您不能具有onClick on组件。 They have to be on DOM elements (Eg. div , button , etc). 它们必须位于DOM元素上(例如divbutton等)。

Here, Button is a component. 在这里, Button是一个组件。 The solution will be to pass in onClick as a prop and attach it to the element in Button component. 解决方案是将onClick作为prop传入,并将其附加到Button组件中的元素。

function Button(props) {
  return <button onClick={props.onClick}>Click Me</button>;
}

This is because onClick is passed as a prop for the button component. 这是因为onClick是作为按钮组件的道具传递的。 As long as you handle the prop inside the component you should be fine. 只要您在组件内部处理道具就可以了。

This should be inside your button component. 这应该在您的按钮组件内部。

render () {
    return <button  onClick={this.props.onClick}/>2</button>;
}

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

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