Skip to content

Commit 870e760

Browse files
committed
feat: 通过 ref 管理非受控组件
1 parent 9158542 commit 870e760

4 files changed

Lines changed: 50 additions & 3 deletions

File tree

React/sandboxs/src/App.jsx

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import React from 'react';
44
// import CoverButton from './test/CoverButton';
55
import Father from './test/Father';
66
import Form from './components/Form';
7+
import { FileUpload } from './components';
78

89
const el = (
910
// 写在 组件中间{ }中的 会自动传入到 props.children
@@ -15,7 +16,14 @@ const el = (
1516
// </CoverButton>
1617

1718
// <Father />
18-
<Form legend={['name','key']}/>
19+
// <Form legend={['name','key']}/>
20+
<FileUpload
21+
accept=".png,.jpg,.pdf"
22+
multiple
23+
onUpload={(files) => {
24+
console.log(files);
25+
}}
26+
/>
1927
)
2028

2129

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import React from 'react';
2+
3+
class FileUpload extends React.Component {
4+
constructor(props) {
5+
super(props);
6+
// 创建 ref,命名采用 xxxRef
7+
this.uploadRef = React.createRef();
8+
}
9+
10+
clickHandle = () => {
11+
// 通过 this.uploadRef.current 获取 input DOM 节点
12+
const files = this.uploadRef.current ? this.uploadRef.current.files : null;
13+
14+
if (!files || !files.length) {
15+
console.log('请先选择文件');
16+
return;
17+
}
18+
19+
console.log(files);
20+
21+
if (typeof this.props.onPick === 'function') {
22+
this.props.onPick(files);
23+
}
24+
};
25+
26+
render() {
27+
const { accept, multiple = false, buttonText = '获取用户输入的内容' } = this.props;
28+
29+
return (
30+
<div>
31+
<input type="file" ref={this.uploadRef} accept={accept} multiple={multiple} />
32+
<button type="button" onClick={this.clickHandle}>{buttonText}</button>
33+
</div>
34+
);
35+
}
36+
}
37+
38+
export default FileUpload;

React/sandboxs/src/components/Layout/index.jsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import React from 'react'
22

3-
function Layout({ children }) {
3+
export default function Layout({ children }) {
44
return <div>{children}</div>;
55
}
66

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
export { default as Input } from './Input'
22
export { default as Form } from './Form'
3-
export { default as Layout } from './Layout'
3+
export { default as Layout } from './Layout'
4+
export { default as FileUpload } from './FileUpload'

0 commit comments

Comments
 (0)