React - 将动态值传递给child

时间:2017-07-14 17:41:58

标签: reactjs parent-child

我有一个通过标准<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;

3 个答案:

答案 0 :(得分:0)

 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?

    componentDidMount(){
     // you can call the getFilesize here        
     this.getFileSize();
    }

         render() {

            return (
               <div className="container">
                 <FileUpload fileSize={this.state.fileSize} />
               </div>
            )
         }
    }

    export default Parent;

子组件

class FileUpload extends Component {
    constructor(props) {
        super(props);
        this.state = { formData: {} };
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    render() {
        return (
            <div className="container">
                <Form
                    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 style={{display:this.props.fileSize > 100 ?  "block": "none" }><h4>File size exceeded.</h4></div>
            </div>
        )
    }
    }

    export default FileUpload;

我认为您希望在文件大小超过给定大小时显示错误消息

您还可以使用componentWillMount来致电getfilesize  它实际上取决于document.getElementById("fileName") 在您的父组件挂载时,特定元素已填充数据,您可以使用componentWillMount生命周期挂钩

答案 1 :(得分:0)

父组件

sudo

子组件

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }
  onFileSelected(e) {

    var fileSize = e.target.files.length > 0 ? e.target.files[0].size : false;
    if (fileSize)
      this.setState({ fileSize });

  }
  render() {

    return (
      <div className="App">
        <input type="file" onChange={this.onFileSelected.bind(this)} />
        <FileUpload fileSize={this.state.fileSize}></FileUpload>
      </div>
    );
  }
}

在上面的代码中我所做的是在父组件中创建class FileUpload extends Component { render() { return ( <div> {this.props.fileSize > 100 ? <h2 >File size exceeds 100</h2> : null} </div> ); } } 并附加了一个onchange事件。

答案 2 :(得分:0)

让它发挥作用。将该功能传递给孩子:

<FileUpload fileSize={this.getFileSize.bind(this)} />

然后在孩子的表格中添加setState onChange来调用该函数:

onChange={({ formData }) => { this.setState({ formData }); this.setState({fileSize:this.props.fileSize()})}}

并相应地显示错误消息:

<div style={{display: this.state.fileSize > 100 ?  "block": "none" }><h4>File size exceeded.</h4></div>