Muh*_*sar 5 components reactjs react-native
I'm new to react native, I'm bit confused about components.
As I created first react native app I saw App.js
the components in App.js created as per following code:
export default function App() {
...
}
Run Code Online (Sandbox Code Playgroud)
and as I saw tutorials many people almost all people making components as per following code:
const FirstComponents = () => {
...
}
Run Code Online (Sandbox Code Playgroud)
I'm also confuse about function components and class based components which created as per following code:
export default class FirstComponents extends Components(){
...
}
Run Code Online (Sandbox Code Playgroud)
What is the difference between function and class base components?
Please provide me answer with examples. Your time will be appreciated.
在 javascript 中,有多种方法可以创建一个函数。例如:
function myFunction () {
//some action
}
const myFunction = () => {
//some action
}
Run Code Online (Sandbox Code Playgroud)
这两个是函数,做同样的事情。
现在您的问题的第二部分是“功能组件和基于类的组件之间有什么区别?”
过去用于控制您state
和生命周期方法(ComponentDidMount 等...)的基于类的组件。如果您不在state
组件或生命周期方法中使用,您将使用基于函数的组件。基本上如果你有一个只有一些 UI 东西的小组件,最好使用功能组件。然而,随着 React 16.8 版,React 团队引入了hooks
.
Hooks 为您的状态和组件生命周期方法等提供了相同的概念。使用钩子你可以控制你的组件,即使它们是功能组件。
前两个片段在声明方面相似。两者都是功能组件。这些与基于类的组件不同。有几个区别:
this
在类组件中进行初始化,但在函数中则不需要this
。 useEffect
hook 用于生命周期钩子,例如componentDidMount
. 举一个简短的例子:
function App(){
const [count, setCount] = useState('');
}
Run Code Online (Sandbox Code Playgroud)
上面的例子"count"
是组件的本地状态属性,setCount
是更新状态的方法。
class App extends React.Component{
constructor(props){
super(props);
this.state = { count: 0 };
this.increaseCount = this.increaseCount.bind(this);
}
increaseCount(){
this.setState({count: this.count+1});
}
// lifecycle methods like componentDidMount, componentDidUpdate etc.
render(){
return(
<button onClick={this.increaseCounter}>INCR</button>
);
}
}
Run Code Online (Sandbox Code Playgroud)
在此类组件中,您可以看到状态是在构造函数中定义的,并使用该setState
方法进行更新。
实时示例会太多,无法添加,因此我建议您使用简单的示例来掌握概念。
归档时间: |
|
查看次数: |
4085 次 |
最近记录: |