Reactjs 如何访问App.js中呈现的组件中的变量
我创建了一个Form.js组件来处理我的表单,并在App.js中呈现它,我想知道如何从App.js中的Form.js访问videoURL、start和end等变量。我看到了另一篇关于使用道具的帖子,当你像这样渲染时,会遇到“videoUrl”、“start”和“end”没有定义 这是我的Form.js文件Reactjs 如何访问App.js中呈现的组件中的变量,reactjs,Reactjs,我创建了一个Form.js组件来处理我的表单,并在App.js中呈现它,我想知道如何从App.js中的Form.js访问videoURL、start和end等变量。我看到了另一篇关于使用道具的帖子,当你像这样渲染时,会遇到“videoUrl”、“start”和“end”没有定义 这是我的Form.js文件 import React, { Component } from 'react' class Form extends Component { constructor(props)
import React, { Component } from 'react'
class Form extends Component {
constructor(props) {
super(props)
this.state = {
video_url: '',
start: 0,
end: 0
}
}
handleVideoUrlChange = (event) => {
this.setState({
videoURL: event.target.value
})
}
handleStartChange = (event) => {
this.setState({
start: event.target.value
})
}
handleEndChange = (event) => {
this.setState({
end: event.target.value
})
}
handleSubmit = (event) => {
event.preventDefault()
}
render() {
const { videoURL, start, end } = this.state
return (
<form onSubmit={this.handleSubmit} method="post">
<div>
<label>Video URL</label>
<input type="text" value={videoURL} onChange={this.handleVideoUrlChange}/>
</div>
<div>
<label>Start</label>
<input type="number" value={start} onChange={this.handleStartChange}/>
</div>
<div>
<label>End</label>
<input type="number" value={end} onChange={this.handleEndChange}/>
</div>
<button type="submit">Submit</button>
</form>
)
}
}
export default Form
因此,您希望从父组件访问子组件的状态。这里有一个方法 步骤1: 首先,您需要在App.js文件中添加一个函数,以从子组件接收数据。在App.js中
const [videoUrl , setVideoUrl] = useState('')
const receiveVideoUrlFromChildren = (videoUrlFromChildren) => {
setVideoUrl(videoUrlFromChildren)
}
步骤2:
然后将此函数传递给子组件。所以在你的App.js return中添加这个
<Form sendDataToParent=(receiveVideoUrlFromChildren) />
因此,现在您可以从父组件访问数据。你可以这样做3次。对于3个变量。或者使用一个函数将所有数据作为一个对象发送。那么App.js是您的父组件,您想在那里访问这些变量吗?如果
App
正在呈现Form
,那么它将无法访问Form
的状态。请参阅将状态移动到共同祖先,即将状态移动到App
并作为道具传递到表单
,正如您在另一篇文章中提到的。在React,父到子组件中,数据沿一个方向流动。第一个选项是将状态移动到父组件(App.js),或者第二个选项是使用React中的Redux或useContext创建全局状态非常感谢您提供的分步教程。
const [videoUrl , setVideoUrl] = useState('')
const receiveVideoUrlFromChildren = (videoUrlFromChildren) => {
setVideoUrl(videoUrlFromChildren)
}
<Form sendDataToParent=(receiveVideoUrlFromChildren) />
handleVideoUrlChange = (event) => {
this.setState({
videoURL: event.target.value
})
this.props.sendDataToParent(event.target.value)
}