加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

React and React with ES6

发布时间:2020-12-15 04:47:22 所属栏目:百科 来源:网络整理
导读:此文章会逐步更新,主要记录使用react遇到的问题和解决方案... React 和 ES6 这个介绍的很完整,看这个吧,https://babeljs.io/blog/2015/06/07/react-on-es6-plus 慢慢开始流行起来,但是React支持不是很好。目前我使用版本是 0.14.0 ES6介绍 用React.Compo

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

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}

其他待更新

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读