2017-08-03 53 views
3

我是新来的react-redux。现在我正在进行一个react-redux项目。当我的输入在输入标签中改变时,我想调用一个函数。为此,我申请“的onchange”事件在这个喜欢如何在react-redux中调用函数

<input {...this.props} onchange="this.callHandler(this.value)"/> 

onchange事件处理程序调用的函数“callHandler”,这是定义为

callHandler = (value) => { 
     console.log("value in input",value); 
} 

我不知道为什么这个功能不叫。
我给这部分完整的代码:

import React from 'react'; 

type PropsType = { 
}; 

export default class InputComponent extends React.Component<void, PropsType, void> { 
    callHandler = (value) => { 
      console.log("value in input",value); 
    } 
    render() { 
     console.log("InputComponent props",this.props); 
    const inputStyle = this.props.inputStyle; 
    return (
     <input {...this.props} onchange="this.callHandler(this.value)"/> 
    ); 
    } 
} 

我也不知道为什么我们使用{...} this.props。
在此先感谢。

回答

2

道具是onChange而不是onchangeonChange预期的功能,而不是字符串

onChange={this.callHandler} 

this.callHandler = event => { 
    console.log('value', event.target.value) 
} 

callHandler被传递一个事件,您可以通过执行event.target.value得到事件的价值目标,如上面。

{...this.props}表示来自组件的所有道具都被传递到输入元素,请参阅spread attributes以供进一步阅读。

例如,

<InputComponent type="text" placeholder="foobar" /> 

通行证InputComponent(在这种情况下类型和占位符)与input元件,创建通用/聪明容器时,其可以是有用的所有道具。

+0

现在它的工作。谢谢。 –

+0

您是否知道我们在此使用{... this.props} –

+0

@Kelltontech,请参阅评论的下半部分。我正在进一步扩展,但希望现在给出一个基本的了解 –

-2

你应该通过功能的onChange,而不是字符串

试试这个:

<input {...this.props} onchange={this.callHandler(this.value)}/> 
+0

不幸的是,这并没有所需的行为。 'onChange'用来代替'onchange'。对于每个渲染而言,调用错字“this.callHandler”时不会发生变化。你可以改为:'onChange = {event => this.callHandler(event.target.value)}',或者'onChange = {this.callHandler}'它不会为每个渲染创建一个新函数并将事件传递给'this.callHandler' –