React基础内容(二)

拆分组件与组件之间的传值

TodoList.js

import React, { Component } from 'react';
import 'antd/dist/antd.css';

import store from './strore/index';
import {getInputChangeAction,getAddItemAction,getDeleteItemAction,getInitList} from './strore/actionCreators';
import TodoListUI from './TodoListUI';


//TodoList这个组件或者说这个类,在js里面一个类里面一定会有constructor构造函数,当我们创建一个TodoList实例
class TodoList extends Component {

	//state是组件里面数据的存放位置
	//一个类里面一定会有constructor构造函数,在React组件中constructor构造函数是优于其它任何函数会自动最先执行的函数
	constructor(props){
		super(props);//TodoList类继承了React的Component类
		//React里面定义数据是定义在state里面的
		this.state = store.getState();
		this.handleInputChange = this.handleInputChange.bind(this);
		this.handleStoreChange = this.handleStoreChange.bind(this);
		this.handleBtnClick = this.handleBtnClick.bind(this);
		this.handleItemDelete = this.handleItemDelete.bind(this);
		store.subscribe(this.handleStoreChange);
	}

	handleInputChange(e){
		const action = getInputChangeAction(e.target.value);
		store.dispatch(action);
	}

	handleStoreChange(){
		this.setState(store.getState());
	}

	handleBtnClick(){
		const action = getAddItemAction();
		store.dispatch(action);
	}
	handleItemDelete(index){
		const action = getDeleteItemAction(index);
		store.dispatch(action);
	}
	componentDidMount(){
		const action = getInitList();
		store.dispatch(action);
		// axios.get('/list').then((res) => {
		// 	const data = res.data.list;
		// 	const action = initListAction(data);
		// 	store.dispatch(action);
		// 	console.log(data); 
		// })
	}
	//父组件通过属性的形式向子组件传递参数,既可以传递数据也可以传递方法
	//子组件通过props接收父组件传递过来的参数
  render() {
    return (
	<TodoListUI 
		inputValue={this.state.inputValue}
		list={this.state.list}
		handleInputChange = {this.handleInputChange}
		handleBtnClick = {this.handleBtnClick}
		handleItemDelete = {this.handleItemDelete}
		/>
	);
  }
}

export default TodoList;

TodoListUI.js

import React from 'react';
import { Input ,Button,List  } from 'antd';

//props是父组件传递过来的内容
const TodoListUI = (props) => {
	return (
		<div style={{marginTop:'10px',marginLeft:'10px'}}>
			<div>
			  <Input value={props.inputValue} placeholder="todo info" style={{width:'300px',marginRight:'10px'}} onChange={props.handleInputChange}/>
			 <Button type="primary" onClick={props.handleBtnClick}>提交</Button></div>
			 <List
			  style={{marginTop:'10px',width:'300px'}}
			  size="small"
			  bordered
			  dataSource={props.list}
			  renderItem={(item,index) => (<List.Item onClick={() => {props.handleItemDelete(index)}}>{item}</List.Item>)}
			  />
		</div>
	  );
}

export default TodoListUI;

子组件调用父组件里的方法然后改变父组件里的数据,只需要把父组件的方法传给子组件就可以了

猜你喜欢

转载自blog.csdn.net/u013565133/article/details/88668270