react的props属性怎样理解?用法是什么?
发布时间:2022-03-02 13:10:01 所属栏目:语言 来源:互联网
导读:在react中的三大属性有state、props、refs,这篇文章给大家分享的是有关react的props属性的内容,小编觉得挺实用的,因此分享给大家做个参考,接下来一起跟随小编看看吧。 类组件 //父组件传值 class Father extends React.PureComponent{ render(){ return
在react中的三大属性有state、props、refs,这篇文章给大家分享的是有关react的props属性的内容,小编觉得挺实用的,因此分享给大家做个参考,接下来一起跟随小编看看吧。 类组件 //父组件传值 class Father extends React.PureComponent{ render(){ return ( <Son value={"son"} /> ) } } class Son extends React.PureComponent{ render(){ return ( <div>this data is {this.props.value}</div> ) } } 函数组件 function Fa(){ return ( <Son value={"son"} /> ) } function Son(props){ return ( <div>this data is {props.value}</div> ) } 在函数组件中,props只需要传一个值就好了,非常方便 在React文档中,对props的解释是 当 React 元素为用户自定义组件时,它会将 JSX 所接收的属性(attributes)以及子组件(children)转换为单个对象传递给组件,这个对象被称之为 “props” 所以,我们通过props能得到父类组件上传的值,也能通过props.children直接得到jsx写成的子组件 props是只读的 React在文档中强调 所有 React 组件都必须像纯函数一样保护它们的 props 不被更改。 纯函数的概念我们已经在redux中解释过了,总而言之,我们不能改变props的值。 组件间通信 现在来总结一下组件间通信: props 首先上一个类组件的写法: //父组件给子组件传值以及说过了,现在总结子组件给父组件传值,此时往往需要父组件给子组件先传一个props函数, //子组件通过调用传入的函数传值改变父组件的值 export default class Fa extends Component { state = {faValue:'Fa1'} changeFa = (value)=>{ this.setState(()=>{ return {faValue:value} }) } render() { return ( <> <h1>Fa's value is {this.state.faValue}</h1> <Son changeFa={this.changeFa}/> </> ) } } export default class Son extends React.PureComponent{ changeValue = ()=>{ this.props.changeFa(this.inputRef.value) } render() { return ( <> <input type="text" placeholder={"请输入您的值"} ref={(el)=>{this.inputRef = el}}/> <button onClick={this.changeValue}>change</button> </> ) } } 然后写一个函数组件的写法: function Fa(){ const [faValue,setFaValue] = useState("Fa1") const changeFa = (value)=>{ setFaValue(value) } return ( <div> <h1>Fa's value is {faValue}</h1> <Son changeFa={changeFa} /> </div> ) } function Son(props){ const inputValue = useRef("") //定义改变fa组件的值的函数 const changeFaValue = ()=>{ props.changeFa(inputValue.current.value) } return ( <> <input type="text" placeholder={"请输入您要改变的值"} ref={inputValue}/> <button onClick={changeFaValue}>change value</button> </> ) } eventbus(订阅-发布机制) 这个可以理解为弱化的redux。这边我们用库pubsub-js来写。写法如下: //比如针对之前的输入案例,我需要给兄弟组件传一个值value,如果不用props,我们该怎么写 Bro: export default class Bro extends Component { componentDidMount() { this.sonData = PubSub.subscribe("brother",(msg,data)=>{ console.log("Bro Component have recived the msg",data); }) } componentWillUnmount() { PubSub.unsubscribe(this.sonData) } render() { return ( <> <div>brother</div> </> ) } } Son: export default class Son extends React.PureComponent{ changeValue = ()=>{ PubSub.publish("brother",this.inputRef.value) } render() { return ( <> <input type="text" placeholder={"请输入您的值"} ref={(el)=>{this.inputRef = el}}/> <button onClick={this.changeValue}>change</button> </> ) } } 这个方法常用的就是三个api,第一个subscribe,发布的相应的事件,并且定义事件要做什么事。第二个是publish,订阅发布的事情,并且传入相应要改变的值。第三个是unsubscribe用来取消发布的事情,做内存的优化。 (编辑:帝国网站管理系统) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |