React and React with ES6

发布时间:2019-07-03 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了React and React with ES6脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

文章逐步更新,主要记录使用react遇到的问题和解决方案...

@H_360_4@

React 和 ES6

这个介绍的很完整,看这个吧,https://babeljs.io/blog/2015/06/07/react-on-es6-plus

慢慢开始流行起来,但是React支持不是很好。目前我使用版本是0.14.0
ES6介绍

用React.component

ES6 Classes官网有介绍

  • 不支持getInITialState,如需在constructor通过this.state={}赋值

  • PRopTyPEs、defaultProps 作为properties定义。

  • 不支持mixins

所以写出来就是这样子

class TodoApp extends React.Component {
    constructor(props){
        super(props); // 需要在第一行
        
        this.state = {};

        // unwork,官网说不支持
        //this.mixins = [xxx];
    }

    render() {
        return (
            <div>
                <button type="button" onClick={this.handleAdd.bind(this)}>add</button>
                <div>
                    {this.props.todos}
                </div>
            </div>
        );
    }

    handleAdd() {
        // something
    }
}

TodoApp.propTypes = {
    todos: React.PropTypes.array.isRequire
};
//TodoApp.defaultProps = { xxx };

由于不支持mixins,大大的遗憾啊。所以React.Component也没有啥用处了。还是不要使用好。

React 相关

key 提示

// 以下代码会提示,确实很烦人。 而且如果不解决,遇到某些场景react还真不更新了,需要引起重视。
// Warning: Each child in an array or iterator should have a unique "key" prop. 
var GridHead = React.createClass({
    render: function () {
        var data = this.props.data;
        return (
            <thead>
            <tr>
                {data.columns.map((col, i) => (<th key={i}>{col.name}</th>))}
            </tr>
            </thead>
        )
    }
});

// 加个key即可
{data.columns.map((col, i) => (<th key={i}>{col.name}</th>))}

空怎么表示

// 有时候需要根据某些条件判断是否显示html,如下三目操作符。 
// 通过chrome控制台可以看到 tr 下面会有个奇怪的 span。
var GridHead = React.createClass({
    render: function () {
        var data = this.props.data;
        return (
            <thead>
            <tr>
                {data.columns.map((col, i) => (<th key={i}>{col.name}</th>))}
                {data.actions.length > 0 ? (<th>操作</th>) : ''}
            </tr>
            </thead>
        )
    }
});

// 换成null
{data.actions.length > 0 ? (<th>操作</th>) : undefined}

其他待更新

脚本宝典总结

以上是脚本宝典为你收集整理的React and React with ES6全部内容,希望文章能够帮你解决React and React with ES6所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。