话不多说直接来看代码吧,这次做的是个简单的增删功能,父组件在input输入框内输入的内容点击提交时要通过子组件作为列表展示在下方,点击任一项则删除相应列表项
index.js,作为入口文件,先将父组件引进来import React from 'react';
import ReactDom,{render} from 'react-dom';
import TodoList from './TodoList';//自己的组件,作为父组件
render(,window.root);
TodoList.js作为本次实例的父组件
1、实现父子传值,通过父组件引用子组件的时候通过属性的方式传递给子组件import React,{Component,Fragement} from 'react';
import TodoItem from './TodoItem';//子组件
class TodoList extends Component{
constructor(props){
super(props);
this.state={
inputValue:"",
list:[]
}
}
render(){
return(
onChange={(e)=>{
this.setState({
inputValue = e.target.value
})
}}
/>
{
this.setState({
list:[...this.state.list,this.state.inputValue]
})
}}>提交
{
this.state.list.map((item,index)=>{
return(
content = {item}
index = {index}
/>
)
})
}
)
}
}
export default TodoList;
TodoItem.js作为子组件,父组件已经将content和index传过来,子组件需要接收并展示,子组件通过this.props.属性名进行接收import React from 'react';
class TodoItem extends React.Component{
constructor(props){
super(props);
}
render(){
return(
{this.props.content})
}
}
2、通过子组件修改父组件的值
父组件 TodoList.jsimport React,{Component,Fragement} from 'react';
import TodoItem from './TodoItem';
class TodoList extends Component{
constructor(props){
super(props);
this.state = {
inputValue = "",
list:[]
}
}
render(){
return(
{
this.setState({
inputValue : e.target.value
})
}}/>
{
this.setState({
list:[...this.state.list,this.state.inputValue]
})
}}>提交
{
this.state.list.map((item,index)=>{
content = {item}
index = {index}
deleItem = {this.deleItemClick.bind(this)}
/>
})
}
)
}
//删除列表项内容的具体逻辑,通过属性传递给子组件,注意需要将函数的this始终指向父组件
deleItemClick(index){
let list = [...this.state.list];
list.splice(index,1);
this.setState({
list:list
})
}
}
export default TodoList
子组件TodoItem.jsimport React,{Component} from 'react';
class TodoItem extends Component{
constructor(props){
super(props);
render(){
return(
(this.props.deleItem(this.props.index)){this.props.content}
)
}