原因是这是一个功能。您需要使用state
而非this.state
来使用它。
,
您没有使用变量state
,而是使用了this.state
。
此外,如果您想在功能中使用state
中的react
,则可能要使用hooks
。
以下链接可以帮助您开始:
状态和生命周期:https://reactjs.org/docs/state-and-lifecycle.html
挂钩状态:https://reactjs.org/docs/hooks-state.html
,
如果您在功能组件或标签render(){...}
中使用变量和函数,则无需使用this
。
import React from 'react';
import './App.css';
import Person from './Person/Person';
function App() {
const state = {
persons: [
{ name: 'max',age: 28 },{ name: 'manu',age: 29 },{ name: 'adel',age: 30 }
]
};
return (
<div className='App'>
<h1> Hello world</h1>
<button> Switch name </button>
<Person
name={state.persons[0].name}
age={state.persons[0].age}
></Person>
<Person name={state.persons[1].name} age={state.persons[1].age}>
hello eslam{' '}
</Person>
<Person
name={state.persons[2].name}
age={state.persons[2].age}
></Person>
</div>
);
}
export default App;
,
您应该使用这样的状态
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
render() {
return (
<div>
<p>You clicked {this.state.count} times</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Click me
</button>
</div>
);
}
}
这是在状态中使用状态的基础,尽管还有另一种在状态中使用状态的方法,即Hooks,这是一个等效的示例:
import React,{ useState } from 'react';
function Example() {
// Declare a new state variable,which we'll call "count"
const [count,setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
有关更多信息,请参见:https://reactjs.org/docs/hooks-state.html
本文链接:https://www.f2er.com/3162018.html