2 回答
TA贡献1869条经验 获得超4个赞
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
TA贡献1812条经验 获得超5个赞
你想象的 React 事件的工作方式在 React 中不起作用,抱歉:(
在 React 中,要有条件地渲染某些东西,条件必须“在渲染内部”,并且必须依赖于状态或提供给组件的道具。
我们只需要改变父组件,你可以尝试:
import React from "react";
import FileUpload from "./FileUpload";
class App extends React.Component {
// Because we need the App component to "change itself",
// we add the variable the condition is based on to the state.
// (in this case, if a file has been selected)
state = {
selected_file: null
};
render() {
return (
<div>
<div>Hey</div>
<input
type="file"
id="my-file"
multiple
onChange={event => {
// When the event happens, update the state with the file from the input
this.setState({
selected_file: event.target.files[0]
});
}}
/>
{/* Only if the file != null (so a file is selected) do we render */}
{this.state.selected_file != null && (
<FileUpload
// I didn't know where `this.displayOnUpload` should come from, so I commented it out
//displayOnUpload={this.displayOnUpload}
test="passed succesfully"
// Pass the file to the child component, so it can use it
file={this.state.selected_file}
/>
)}
</div>
);
}
}
export default App;
我希望评论能让你了解它是如何工作的:)
如果没有,我会从 React 课程开始,因为 React 状态是一个在你开始时需要掌握的概念。我无法在 Stack Overflow 的帖子中教你这么好!
添加回答
举报