【问题标题】:react typescript pass membervariables反应打字稿传递成员变量
【发布时间】:2019-01-02 10:41:30
【问题描述】:

我的组件 Child 有一个可以明显改变的成员变量。 但是,据我所知,我只能通过 PROPS 和 STATES。我知道我可以通过 PROPS 或其他参数传递我的成员变量,但是没有更漂亮的解决方案吗?

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;
    }
}

【问题讨论】:

    标签: reactjs typescript tsx


    【解决方案1】:

    这正是状态的设计目的:

    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});
        }
    }
    

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

    【讨论】:

    • 这是真的,状态就是这样,但是使用打字稿你可以定义成员变量,无论你为什么应该或不应该这样做,问题是:我可以读出或传递我的成员变量吗?方式?
    • 我不确定我是否理解“以通用方式读取或传递我的成员变量”的意思。你可以说得更详细点吗?如果您的意思是要使用它们来渲染组件,那么正如您所看到的,您可以在 render 方法中读取它们,但是当成员变量更改时,您需要以某种方式通知 React 您的组件需要重新呈现。如果您使用状态,则在您更改状态时会自动重新渲染。
    猜你喜欢
    • 1970-01-01
    • 2016-09-05
    • 1970-01-01
    • 2014-10-13
    • 1970-01-01
    • 2019-07-11
    • 2021-06-30
    • 1970-01-01
    • 2021-11-10
    相关资源
    最近更新 更多