react的状态提升

<body>
    <div id="app">
    </div>
    <script type="text/babel">
       class Dollar extends React.Component{
            constructor(props) {
                super(props);
                this.handleChange = this.handleChange.bind(this);
            }

            handleChange(event) {
                this.props.dollarChange(event.target.value); //将子组件的值通过props传给父组件
            }

            render() {
                const money = this.props.money;
                const yuan = this.props.yuan;
                const text  = this.props.type == 'd' ? '美元' : '人民币';
                return <fieldset>
                    <legend>{text}</legend>
                    <input value={money} onChange={this.handleChange}/>    
                </fieldset>
            }
        }

        class Box extends React.Component{
            constructor(props){
                super(props);
                this.state = {
                    dollar: '',
                    yuan: '',
                };
                this.dollarInput = this.dollarInput.bind(this);
                this.yuanInput = this.yuanInput.bind(this);
            }

            dollarInput(value) {
                if (parseFloat(value) || value == '' || parseFloat(value) == 0) {
                    this.setState({
                        dollar:  value,
                        yuan:   value == '' ? '' : value * 6.9977
                    });
                } else {
                    alert('输入值必须为数字。');
                }
            }

            yuanInput(value) {
                if (parseFloat(value) || value == '' || parseFloat(value) == 0) {
                    this.setState({
                        dollar: value == '' ? '' : value * 0.1429,
                        yuan: value,
                    });
                } else {
                    alert('输入值必须为数字。');
                }
            }
            render() {
                return <div>
                    <Dollar type = {'d'} dollarChange = {this.dollarInput} money = {this.state.dollar}/>
                    <Dollar type = {'y'} dollarChange = {this.yuanInput} money = {this.state.yuan}/>
                </div>
            }
        }

        ReactDOM.render(
                <Box />,
                document.getElementById('app')
            );
    </script>
</body>
原文地址:https://www.cnblogs.com/Yangyecool/p/13394556.html