基本渲染
将变量的值直接显示到页面中。在jsx中可以在大括号直接编写Js代码,如果是变量,则直接输出。
function Welcome(props) {
let msg = 'hello world'
return <h1>{msg}</h1>;
}
列表渲染
可以通过使用 {} 在 JSX 内构建一个元素集合, key给数组中的每一个元素赋予一个确定唯一的标识
<ul className="list">
{
props.map((item,index) => return <li key={index}>{item}</li>)
}
</ul>
条件渲染
React中的条件渲染和JavaScript中的一样,使用JavaScript运算符if或者条件运算符去创建元素来表现当前的状态,然后让React根据它们来更新UI
function UserInfo(props){
let {user} = props;
if(user) {
return (
<div>欢迎您 {user.name} 头像</div>
)
}
return (
<div><a href="#">亲,请登录</a></div>
)
}
组件传值
//组件名称必须首字母大写
function MyCom(props){
//props就是从父组件接受过来的参数组成的对象 props={msg:'hello',age:'12'}
//返回一个模板
return <h1>{props.msg}</h1>;
}
let msg = 'hello'; //父组件
ReactDOM.render(<MyCom msg={msg} age="12"/>,document.getElementById('root'))
参数的传递,父子组件通信
1.在子组件使用的时候,写属性名=属性值。这里的属性名和属性值,会存到props对象中。在函数声明组件,props在函数的形参这里。
2.在子组件的内部,可以使用{props.属性名}
传递字符串
<MyComponent foo='this is foo' />
传递数字
<MyComponent foo={1,2,3} /> 3 //是错误的写法,只会传入最后一个值
传递布尔类型
<MyComponent foo={true} />
传递数组类型
<MyComponent foo={[1,2,3,4]} /> 1234
传递对象
<MyComponent foo={{name: 'terry' }} />