我正在尝试与子组件通信,但仅遵循 onChange
事件<input>
html 元素。谁能向我解释为什么这两个组件似乎没有通信,以及为什么子组件中的 console.log 没有显示?
家长
import React from 'react';
import FileUpload from './FileUpload'
class App extends React.Component {
callChild = ()=>{
return (
<FileUpload displayOnUpload = {this.displayOnUpload} test = 'passed succesfully'/>
)
}
render(){
return (
<div>
<input
type="file"
id = "my-file"
multiple
onChange = {()=>this.callChild()}
/>
</div>
)
}
}
export default App
child
const FileUpload = (props)=> {
console.log(props.test)
return (
<div>
hi
</div>
)
}
export default FileUpload
最佳答案
onChange 将调用方法(函数),但不会呈现任何内容。您可以使用状态有条件地渲染组件。
import React from 'react';
import FileUpload from './FileUpload'
class App extends React.Component {
state = {
fileChanged = false
}
callChild = ()=>{
this.setState({ fileChanged: true })
}
render(){
if (this.state.fileChanged) {
return <FileUpload displayOnUpload = {this.displayOnUpload} test = 'passed succesfully'/>
}
return (
<div>
<input
type="file"
id = "my-file"
multiple
onChange = {()=>this.callChild()}
/>
</div>
)
}
}
export default App
关于javascript - 在 onChange 事件之后有条件地渲染子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57261036/