一、第一种方法 父组件
import React from 'react';
import Input from './Input';
const TodoList = () => {
const handleSearch = (e:string):void => {
console.log('调用当前子组件的方法', e);
};
return (
<div className='todolist'>
<Input handleSearch={handleSearch}/>
</div>
);
};
export default TodoList;
子组件
import React from 'react';
interface middleProps {
handleSearch: (e:string) => void; //其实是function
}
const Input: React.FC<middleProps> = (prop) => {
const { handleSearch } = prop;
return (
<button onClick={() => {
handleSearch('666');
}}>点击</button>
);
};
export default Input;
二、第二种方法
父组件
import React ,{useState}from 'react';
import Input from './Input';
const TodoList = () => {
const [value,setValue] = useState<number>(0)
return (
<div className='todolist'>
<Input handleValue = {(code:number)=>{setValue(code)}} childValue = {value}/>
{value}
</div>
);
};
export default TodoList;
子组件
import React from 'react';
interface middleProps {
handleValue:Function;
childValue: number
}
const Input: React.FC<middleProps> = (prop) => {
let { childValue, handleValue } = prop;
return (
<button onClick={() => {
handleValue(childValue+1)
}}>点击</button>
);
};
export default Input;
三、应用场景 todolist
父组件
import React, { useState } from 'react';
import Input from './Input';
const TodoList = () => {
let [value, setValue] = useState<any[]>([]);
const getItem = (code: any) => {
setValue([...value, code]);
};
return (
<div className='todolist'>
<Input handleValue={getItem} />
<ul>
{
value.map((item: string, index) => {
return <li key={index}>{item}</li>;
})
}
</ul>
</div>
);
};
export default TodoList;
import React,{useState}from 'react';
interface middleProps {
handleValue: Function;
}
const Input: React.FC<middleProps> = (prop) => {
let { handleValue } = prop;
const [value,setValue] = useState<string>("")
const getItem = (event:any) =>{
setValue(event.target.value)
};
const addItem=()=>{
handleValue(value)
setValue("")
}
return (
<div>
<input type='text' placeholder={'请输入'} value={value} onChange={(event) => {
getItem(event);
}} />
<button onClick={() => {
addItem()
}}>添加
</button>
</div>
);
};
export default Input;