前言
有时候为了写代码的时候。使其组件化程度更高,很多地方都需要用到传值,并且有回传,这个地方就比较麻烦,特别是使用typescript这种语法的时候,这里简单记录一下怎么传值
父传子
这个相对比较简单,直接将值放在组件中,然后子组件中接受获取就行了
父组件中内容
{countStatusDurationMap && countStatusAlterNumMap && <SingleDevice setDeviceId={setDeviceId} countStatusDurationMap={countStatusDurationMap} countStatusAlterNumMap={countStatusAlterNumMap} deviceListMap={deviceOptions}/> }
子组件中内容
type DeviceListProps = {
code:string,
name:string,
items:CodeNameProps[]
}
interface DataChart {
countStatusDurationMap: CountStatusDurationProps,
countStatusAlterNumMap:CountStatusAlterNumProps,
deviceListMap:DeviceListProps[],
setDeviceId:any
}
const SingleDevice:FunctionComponent<DataChart> = (props) => {
通过props。。。获取
}
子传父
比如有一个点击事件,需要从子组件中执行这个点击操作,但是父组件中需要用到这个值,没得办法,只能传了。
首先声明一个usestate
const [deviceId, setDeviceId] = useState()
然后在传入
<SingleDevice setDeviceId={setDeviceId}/>
子组件接受
然后点击事件οnclick={handlechange方法}
function handleChange(value:any) {
// setOptionValue(value)
props.setDeviceId(value[1])
console.log(value)
}
这样在父组件中声明的deviceId就发生了变化。