zoukankan      html  css  js  c++  java
  • 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>
  • 相关阅读:
    BOM与DOM
    前端基础之JavaScript
    前端基础之css
    前端基础之HTML
    索引与慢查询优化
    视图、触发器、事务、存储过程、函数、流程控制
    pymysql模块
    mysql的基本查询语句及方法
    ie6 select选中问题
    offsetLeft
  • 原文地址:https://www.cnblogs.com/Yangyecool/p/13394556.html
Copyright © 2011-2022 走看看