infernojs将数据传递给父组件

时间:2017-02-09 22:55:52

标签: typescript infernojs

我被困在我的简单 infernojs v1.2.2 应用程序中以将数据传递给父组件,这个问题可能与打字稿有关,因为我得到了一些错误的打字稿而不是(它有问题)识别来自父组件的道具。)

我尝试给我的子组件回调以便稍后调用它,但是我的上下文不好。我的工作确实让我甚至没有触发onInput。

这是我的父组件

import { linkEvent } from 'inferno';
import Component from 'inferno-component';


import Weight from './weight';

export class RatioAlcohol extends Component<Props, any> {
    constructor(props, context) {
        super(props, context);
         this.state = { weight: 65 };
    }
    setChangeWeight(instance, event) {
        instance.setState({ weight: event.target.value });
    }
    render(props){
        return (
                <div className="ratio-alcohol">
                    <Weight valueChanged={ linkEvent(this, this.setChangeWeight) } weight={ this.state.weight } />
                </div>
        );
    }
}

还有我的孩子组件:

import { linkEvent } from 'inferno';
import Component from 'inferno-component';

export default class Weight extends Component<Props, any> {
    constructor(props, context) {
        super(props, context);
        this.state = { weight: props.weight};
    }
    handleChangeWeight(instance, event) {
        instance.valueChanged.event();
    }
    render(props){
        return (
                <div className="weight">
                    <label for="WeightInput">What is your weight(Kg)?</label>
                    <input id="WeightInput" name="weight" type="number" value={ props.weight } onInput={ linkEvent(props, this.handleChangeWeight) } />
                </div>
        );
    }
}

我没有在inferno文档中找到父/子组件交互的例子,我没有React的经验,我觉得我可以从React app得到答案,但暂时没有得到它。

我使用了inferno-typescript-example作为我项目的基础,我不知道这个问题是否重要。

1 个答案:

答案 0 :(得分:1)

因此handleChangeWeight中的Weight函数签名具有第1个参数作为实例,它实际上是您的组件的props。它应该像

export default class Weight extends Component<Props, any> {
    constructor(props, context) {
        super(props, context);
        this.state = { weight: props.weight};
    }
    handleChangeWeight(props, event) {
        props.valueChanged(event);
    }
    render(props){
        return (
                <div className="weight">
                    <label for="WeightInput">What is your weight(Kg)?</label>
                    <input id="WeightInput" name="weight" type="number" value={ props.weight } onInput={ linkEvent(props, this.handleChangeWeight) } />
                </div>
        );
    }
}

并且在RatioAlcohol中你不必链接事件,而是如果你需要访问实例,你必须绑定你的处理程序

export class RatioAlcohol extends Component<Props, any> {
    constructor(props, context) {
        super(props, context);
        this.state = { weight: 65 };
        this.setChangeWeight = this.setChangeWeight.bind(this)
    }
    setChangeWeight(event) {
        this.setState({ weight: event.target.value });
    }
    render(props){
        return (
                <div className="ratio-alcohol">
                    <Weight valueChanged={ this.setChangeWeight } weight={ this.state.weight } />
                </div>
        );
    }
}