我正在开发一个用react-redux编写的项目。我想在组件中使用组件状态而不是全局状态 我的组件代码是:
import React from 'react';
import Input from 'src/containers/Input';
type StateType = {
searchChannel: string
};
export default class AddChannelComponent extends React.Component < void,
PropsType,
void > {
state : StateType;
constructor(props : PropsType) {
super(props);
this.state = {
searchChannel: 'test'
};
}
inputHandler(value) {
console.log("text isdddd", value);
this.setState({searchChannel: value}); <==Error Occur Here
}
render() {
return (
<div >
<p>Type your input</p>
<div>
<Input inputHandler={this.inputHandler} placeholder="Search all public channels..."/>
</div>
</div>
);
}
}
input子函数由子组件调用。在这个this.setState({searchChannel:value})里面给出了一个错误,即this.setState不是一个函数。虽然我在构造函数中为searchChannel分配了一个测试值,但是当我在渲染中控制它的值时它正在工作。
答案 0 :(得分:3)
我的更正将是这样的
import React from 'react';
import Input from 'src/containers/Input';
export default class AddChannelComponent extends React.Component{
constructor(props) {
super(props);
this.state = {
searchChannel: 'test'
};
}
inputHandler = (value) => {
console.log("text is dddd", value);
this.setState({searchChannel: value});
}
render() {
return (
<div >
<p>Type your input</p>
<div>
<Input inputHandler={this.inputHandler} placeholder="Search all public channels..."/>
</div>
</div>
);
}
}
如果您传递instance method
(指的是特定的上下文,也就是访问this
),您将失去其原始上下文,因为它取决于来电者。
此处的详细信息:How to access the correct `this` inside a callback?
例如:inputHandler={this.inputHandler}
保持this
你可以:
inputHandler={this.inputHandler.bind(this)}
inputHandler={(...args) => this.inputHandler(...args)}
imputHandler = () => {}
答案 1 :(得分:0)
import React from 'react';
import Input from 'src/containers/Input';
export default class AddChannelComponent extends React.Component{
constructor(props) {
super(props);
this.state = {
searchChannel: 'test'
};
}
inputHandler = (value) => {
console.log("text is dddd", value);
this.setState({searchChannel: value});
}
render() {
return (
<div >
<p>Type your input</p>
<div>
<Input inputHandler={this.inputHandler.bind(this)} placeholder="Search all public channels..."/>
</div>
</div>
);
}
}