美文网首页
入门篇(二)

入门篇(二)

作者: wn_Smile | 来源:发表于2016-11-30 10:08 被阅读28次
例子:把数组里边的图片渲染到页面上
//1.生成一个组件类
class Imgs extends Component {
 //2.constructor是类的默认方法,通过new命令生成对象,实例化时,自动调用该方法
    constructor(props) {
        //super关键字很重要,如果要在 constructor里用到this、那么必须写super(),否则新建实例时会报错
        super(props);
        //绑定this
        this.handleClick = this.handleClick.bind(this);
    }
    //点击事件的函数
    handleClick(event) {
    }
    render() {
    //传入imgs、下边map遍历的时候调用(渲染组件时,里边的属性都要用this.props传入)
        const {
            imgs
        } = this.props
        return (
            <div className="content">
                {
                    //map遍历、需要指定key值,要不会报警告、map里边需要return返回(=> ES6写法、相当于function)
                    imgs.map((item,index) =>{
                        return(
                            <div key={index} onClick={this.handleClick}>
                                <img 
                                    src={item} 
                                    data-index={index}
                                />
                            </div>                                                      
                        )   
                                                
                    })  
                }
            </div>
        )
    }
};
//把图片的url放入数组中
const json = [
    '../images/1.jpg',
    '../images/2.jpg',
    '../images/3.jpg',
];
ReactDOM.render(
//渲染组件、组件的属性img的值是图片url数组
    <Imgs 
        imgs={json}
    />,
    document.getElementById('root')
);

相关文章

网友评论

      本文标题:入门篇(二)

      本文链接:https://www.haomeiwen.com/subject/vrozpttx.html