欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 家装 > React-组件和props

React-组件和props

2025/4/28 0:16:11 来源:https://blog.csdn.net/qq_40007317/article/details/147469983  浏览:    关键词:React-组件和props

 1、类组件

import React from 'react';
class ClassApp extends React.Component {constructor(props) {super(props);this.state={};}render() {return (<div><h1>这是一个类组件</h1><p>接收父组件传过来的值:{this.props.name}</p></div>);}
}
export default ClassApp;

2、函数组件

import React from 'react';
function FuncApp(props) {return (<div><h1>我是函数组件</h1><h2>接收父组件传过来的值:{props.name}</h2></div>);
}

3、组件样式控制

import './index.css';
function FuncApp(props) {return (<div><h1 style={{ color: 'red', fontSize: 25 }}>我是函数组件</h1><h2 className='info-box'>接收父组件传过来的值:{props.name}</h2></div>);
}// index.css
.info-box {color: skyblue;font-size: 25px;
}

4、React表单组件

React中的表单组件大致可分为两类:

  • 受控组件:一般涉及到表单元素时我们才会使用这种分类方法。受控组件的值由props或state传入,用户在元素上交互或输入内容会引起应用state的改变。在state改变之后重新渲染组件,我们才能在页面中看到元素中值的变化,假如组件没有绑定事件处理函数改变state,用户的输入是不会起到任何效果的,这也就是“受控”的含义所在。
  • 非受控组件:类似于传统的DOM表单控件,用户输入不会直接引起应用state的变化,我们也不会直接为非受控组件传入值。想要获取非受控组件,我们需要使用一个特殊的ref属性,同样也可以使用defaultValue属性来为其指定一次性的默认值。
//受控组件
this.state = {value: "默认值"
}
change(event) {this.setState({value: event.target.value})
}
<div><input type="text" value={this.state.value} onChange={this.change.bind(this)} /><p> {this.state.value} </p>
</div>// hooks写法
import { useState } from "react";
function App() {const [name, setName] = useState('')return (<div className="App"><input type="text" value={name} onChange={(e) => setName(e.target.value)} /></div>);
}
export default App;//非受控组件
<input type="text" defaultValue="hello!"/>

5、React获取dom元素

        在react中操作dom,可以使用useRef钩子函数

(1)使用useRef创建ref对象,并于JSX绑定

import { useRef } from "react";
function App() {const inputRef = useRef(null)return (<div className="App"><input type="text" ref={inputRef} /><button onClick={showDom}>显示dom</button></div>);
}
export default App;

(2)在DOM可用时,通过inputRef.current拿到DOM对象

const showDom = () => {console.log(inputRef.current);
}

6、props

(1)定义和使用props

        react中的每一个组件,都包含有一个属性(props),属性主要是从父组件传递给子组件的 

// 父组件
function App() {const name = '张三'return (<div className="App"><Son name={name} /></div>);
}// 子组件
function Son(props) {return (<div>{ props.name }</div>)
}

(2)特殊的prop children(类似于Vue的插槽)

        当我们把内容嵌套在子组件标签中时,父组件会自动在名为children的prop属性中接收该内容

// 父组件
function App() {const name = '张三'return (<div className="App"><Son name={name}><span>hello</span></Son></div>);
}// 子组件
function Son(props) {return (<div>{ props.children }--{ props.name}</div>)
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词