Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/facebook/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 反应类型脚本传递成员变量_Reactjs_Typescript_Tsx - Fatal编程技术网

Reactjs 反应类型脚本传递成员变量

Reactjs 反应类型脚本传递成员变量,reactjs,typescript,tsx,Reactjs,Typescript,Tsx,我的子组件有一个membervariable,它可以明显地更改。 然而,据我所知,我只能传递道具和状态。我知道我可以通过道具或其他参数传递membervariables,但是没有更好的解决方案吗 class Child extends React.Component<any,any> { private anyValue:string; constructor(props) { this.change = this.change.bind(this);

我的子组件有一个membervariable,它可以明显地更改。 然而,据我所知,我只能传递道具和状态。我知道我可以通过道具或其他参数传递membervariables,但是没有更好的解决方案吗

class Child extends React.Component<any,any> {
    private anyValue:string;
    constructor(props) {
        this.change = this.change.bind(this);
    }
    public render() {
        return (
            <input onChange={this.change} value={this.anyValue}/>
        );
    }
    private change(e:any) {
        this.anyValue = e.target.value;
    }
}
类子级扩展React.Component{
私有值:字符串;
建造师(道具){
this.change=this.change.bind(this);
}
公共渲染(){
返回(
);
}
私人变更(e:任何){
this.anyValue=e.target.value;
}
}

这正是状态的设计目的:

class Child extends React.Component<any,{anyValue: string}> {
    constructor(props) {
        super(props);
        this.change = this.change.bind(this);
    }
    public render() {
        return (
            <input onChange={this.change} value={this.state.anyValue}/>
        );
    }
    private change(e:any) {
        this.setState({anyValue: e.target.value});
    }
}
类子级扩展React.Component{
建造师(道具){
超级(道具);
this.change=this.change.bind(this);
}
公共渲染(){
返回(
);
}
私人变更(e:任何){
this.setState({anyValue:e.target.value});
}
}

您唯一的其他选择是使用
forceUpdate

这是正确的,状态是这样的,但是使用typescript您可以定义membervariables,无论您为什么应该或不应该这样做,问题是:我可以以通用方式读出或传递我的membervariables吗?我不确定我是否理解您的意思“以通用方式读取或传递我的成员变量“.你能说得更具体些吗?如果您想使用它们来渲染组件,那么正如您所看到的,您可以在
render
方法中读取它们,但是当成员变量更改时,您需要以某种方式通知React您的组件需要重新渲染。如果使用状态,则更改状态时会自动重新渲染。