从子组件访问onChange事件(React / Redux) [英] Accessing onChange event from child component (React/Redux)

查看:269
本文介绍了从子组件访问onChange事件(React / Redux)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个容器组件,它使用输入呈现子组件。我想在 onChange 事件期间访问子组件的值,但我得到一个代理对象而不是输入值。

I have a container component that's rendering a child component with an input. I would like to have access to the child component's value during the onChange event, but I am getting a "Proxy" object instead of the input value.

容器组件

...

class InputContainer extends React.Component {

    handleChange = (val) => {
        console.log(val);

        // => Proxy { [[Handler]]: Object, [[Target]]: SyntheticEvent, [[isRevoked]]: false }
    }

    render() {
        return <Input handleChange={this.handleChange} {...this.props} />;
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(InputContainer);

输入组件

export default function Input(props) {
    return <input onChange={props.handleChange} />;
}

为什么我会得到这个代理对象?我怎么能从 InputContainer 获取输入值?

Why am I getting this "Proxy" object and how can I get the input's value from InputContainer?

推荐答案

什么你看到的是React的 SyntheticEvent 的一个实例。请注意,一切都会起作用,即这应该有效:

What you are seeing is an instance of React's SyntheticEvent. Note that everything will work the same, i.e this should work:

console.log('ev -> ', ev.target.value);

但是,如果你想看到开发者工具中的值,请尝试:

However, if you want to see the values in the Developer tools try:

console.log('ev -> ', ev.nativeEvent);

资料来源: https://facebook.github.io/react/docs/events.html

引用:


您的事件处理程序将传递SyntheticEvent的实例,这是一个围绕浏览器本机事件的跨浏览器包装器。它具有与浏览器本机事件相同的接口,包括stopPropagation()和preventDefault(),但事件在所有浏览器中的工作方式相同。
如果由于某种原因发现您需要底层浏览器事件,只需使用nativeEvent属性即可获取它。

Your event handlers will be passed instances of SyntheticEvent, a cross-browser wrapper around the browser's native event. It has the same interface as the browser's native event, including stopPropagation() and preventDefault(), except the events work identically across all browsers. If you find that you need the underlying browser event for some reason, simply use the nativeEvent attribute to get it.

这篇关于从子组件访问onChange事件(React / Redux)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆