列表遍历&Key
像vue中的v-for指令在React里遍历数组对象用map,循环遍历必须加key,key必须是在数组中唯一的,尽量不绑定index,否则 数组更新数据了 但ui界面没有更新,DOM渲染的时候,是根据Key值的不同 新旧对比来替换的。
export default class Items extends React.Component{
// constructor(props){
// super(props)
// }
// componentDidMount(){
// console.log('dd',this.props)
// }
render(){
return (<ul>
{
this.props.arr.map((item)=>{
return <li key={item.nums}>
<h1>{item.tiele}</h1>
<p>{item.nums}</p>
</li>
}
)
}
</ul>)
}
}
React中的组件样式私有化:
在VUE中:直接在设置stye时,添加scoped属性,这样,在vue编译时就会对style私有化处理,使得样式只会在当前组件下私有.
而在react中为了避免组件间的样式相互污染有以下几种方法:
方式一:给DOM起独一无二的类名。
方式二:写行内样式。
方式三:[name].module.scss方法,给样式文件起名加.module。
组件间通信:
父--->子:父向子通过Props属性传递
<子组件名 属性名={属性值}/>
子组件读取props:props.属性名(this.props.属性名)
子--->父:利用回调函数,父组件将一个函数作为 props 传递给子组件,子组件调用该回调函数,便可以向父组件通信。
<子组件名 自定义事件名={父组件这边的事件}/>
子组件调用props中的自定义事件并传参,
子组件:
父组件
插槽:插槽是子组件提供给父组件使用的一个占位符。
在vue中 我们用<slot></slot>标签表示,父组件在引入这个占位符中填充其他组件或者dom.
在react用props.children表示插槽
但是props.children是将<Items>标签中所有的内容都包含在里面里,有时候需要分开几个位置插入,就不能使用children了,直接将插入组件当成props传入。
//子组件
import React from "react"
import style from './item.module.scss'
export default class Items extends React.Component{
constructor(props){
super(props)
this.state={
inValue:''
}
}
componentDidMount(){
// console.log('dd',this.props)
}
changeHandle=(e)=>{
this.setState(()=>({
inValue:e.target.value
}))
this.props.ChangValue(e.target.value)
}
render(){
return (
<div className={style.item}>
<p>
<input type='text' value={this.state.inValue} onChange={this.changeHandle}></input>
</p>
<div>
这是左边:{this.props.left}
</div>
<p>
这是右边:{this.props.right}
</p>
{/* <ul>
{
this.props.arr.map((item)=>{
return <li key={item.nums}>
<h1>{item.tiele}</h1>
<p>{item.nums}</p>
</li>
}
)
}
</ul> */}
</div>)
}
}
//父组件
import React from "react";
import Items from "../item/index";
import Move from "../move/index"
class CommentList extends React.Component {
constructor(props) {
super(props);
this.state = {
time: new Date(),
number: 0,
text:''
};
}
onChangValue=(value)=>{
this.setState((state)=>({
text:value
}))
}
render() {
return (
<div>
<Items arr={this.state.arr} ChangValue={this.onChangValue} left={<Move></Move>} right={'youyouyouyouuyyy'}>
我是插槽啊 钥匙孔呀
</Items>
</div>
);
}
}
export default CommentList;
嘿嘿嘿今天周五,周末再学高阶组件(HOC)