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




随时随地看视频
热门评论
-
慕后端25760882019-06-09 0
-
Time_True_Lee2019-05-24 0
查看全部评论同意
这丧心病狂的文章格式