安装和使用
npm i -g create-react-app
create-react-app my-app
cd my-app
npm start
简单Demo
<div id="example"></div>
<script type="text/babel">
ReactDOM.render(
<h1>Hello, world!</h1>,
document.getElementById('example')
);
</script>
ReactDOM.render接收两个参数,第一个是要渲染的数据,第二个是渲染的地方
传值
1.父传子
// 子组件sayHi.js
function SayHi(props) {
return (
<div>
<h2>你好啊{props.name}</h2>
<h2>你好啊{props.name2}</h2>
</div>
)
}
export default SayHi
// 子组件sayHello.js
function SayHello(props) {
return (
<div>
<h2>你好啊{props.name}</h2>
</div>
)
}
export default SayHello
// 父组件
import SayHi from './sayHi'
import SayHello from './SayHello'
function App() {
let obj = {
name:'景天',
name2:'雪见',
}
return (
<div className="App">
// 复杂传值
<SayHi obj={obj} />
// 简单传值
<SayHello name="雪见" />
</div>
);
}
export default App;
2.子传父
第一种:父组件传递一个函数给子组件
缺点:如果有多层嵌套,需要一级一级的把函数往下传
// 父组件中内容
import React, { Component } from 'react'
import './index.scss'
import InputBox from './components/Input'
export default class TodoList extends Component {
state = {
list: [
{id:1,name:'景天',isCheck:true},
{id:2,name:'雪见',isCheck:true},
{id:3,name:'徐长卿',isCheck:false},
{id:4,name:'紫萱',isCheck:false},
{id:5,name:'龙葵',isCheck:true}
]
}
// 父组件定义一个方法传给子组件,子组件在需要的时候触发这个函数,父组件拿到子组件传进来的值,进行自己需要的操作即可。
addList = (obj) => {
const newList = [obj,...this.state.list]
this.setState({
list: newList
})
}
render() {
const {list} = this.state
const {addList} = this
return (
<div className="main">
<InputBox addList={addList} />
</div>
)
}
}
// 子组件中内容
import React from 'react'
export default class InputBox extends React.Component {
// 子组件的按键事件触发
handleAddList = (e)=> {
if (e.keyCode !== 13 || e.target.value.trim() === '') return
const tempObj = {id: new Date().getTime(),name: e.target.value, isCheck: false}
// 把获取到的值放到父组件传递过来的函数中
this.props.addList(tempObj)
e.target.value = ''
}