如何在React中访问JSX组件方法?

时间:2019-04-24 23:27:53

标签: reactjs react-final-form filepond

我正在将FilePond与react-final-form一起使用。我不知道如何访问FilePond适配器的方法。 FilePond有一个我尝试访问的getFiles方法。

const FileAdapter = ({ input: {value, onChange, ...rest}, pond}) => (
  <FilePond
    ref={pond}
    onprocessfiles={console.log(pond.getFiles())}
    />
)


class ContactForm extends React.Component {
  constructor(props) {
    super(props);
    this.pond = React.createRef();
  }
    render() {
        return (
            <>
            <Form
              render={) => (
                <form>
                    <Field name="files" pond={this.pond} component={FileAdapter} />
                </form>
              )}
            />
            </>
        );
    }
}

我每次都会收到以下信息:

  

TypeError:无法读取未定义的属性'getFiles'

2 个答案:

答案 0 :(得分:0)

您需要使用thiscurrent,请参见https://reactjs.org/docs/refs-and-the-dom.html#creating-refs

<FilePond
    ref={ this.pond }
    onprocessfiles={ () => console.log( this.pond.current.getFiles() ) }
    />

答案 1 :(得分:0)

您的onprocessfiles应该是回调。

onprocessfiles={() => console.log(pond.getFiles())}

实际上,您正在第一个渲染器上调用pond.getFiles(),并且尚未填充参考。