我有一个应用程序通过标准的<input type="file"/>
上传文件。我试图将所选文件的文件大小传递给孩子,以查看它是否超过特定大小,如果是,则显示错误。我知道你必须将状态值作为道具传递下来,但我不确定在哪里/如何调用函数来获取更新的值。任何帮助表示赞赏。React - 将动态值传递给儿童
编辑:我正在使用反应jsonschema窗体来构建窗体:https://github.com/mozilla-services/react-jsonschema-form。在Parent类之前声明模式。
家长
const schema = {
type: 'object',
required: ['file'],
properties: {
file: { type: 'string', format: 'data-url', title: 'File' }
}
}
const FileWidget = (props) => {
return (
<input type="file" id="fileName" required={props.required} onChange={(event) => props.onChange(event.target.value)} />
)
}
const uiSchema = {
file: {
'ui:widget': FileWidget,
classNames: "uiSchema"
}
}
class Parent extends Component {
constructor(props) {
super(props);
this.state = { fileSize: 0 };
this.getFileSize = this.getFileSize.bind(this);
getFileSize(){
this.setState({fileSize: document.getElementById("fileName").files[0].size});
console.log("FILESIZE:: ", this.state.fileSize);
} //where to call to update the file size?
render() {
return (
<div className="container">
<FileUpload schema={schema} uiSchema={uiSchema} fileSize={this.state.fileSize} />
</div>
)
}
}
export default Parent;
儿童
class Child extends Component {
constructor(props) {
super(props);
this.state = { formData: {} };
this.handleSubmit = this.handleSubmit.bind(this);
}
render() {
return (
<div className="container">
<Form
schema={this.props.schema}
uiSchema={this.props.uiSchema}
formData={this.state.formData}
onChange={({ formData }) => this.setState({ formData })}
onSubmit={this.handleSubmit}
>
<div>
<button type="submit" className="btn btn-info">Convert</button>
</div>
</Form>
<div hidden={this.props.fileSize > 100 ? false : true }><h4>File size exceeded.</h4></div>
</div>
)
}
}
export default Child;
那是对的。但是,如果我在componentDidMount中调用该函数,则只会在组件第一次呈现时调用该函数。每次用户在同一页面中选择一个新文件时,我都需要它来调用它。 – user7674254