虽然React的虚拟DOM优雅地处理你遇到的大多数情况,但有些情况下你需要与实际元素进行交互。
创建一个ref
创建一个ref是相当简单的;只需传递一个调用,分配给一个财产。
1class MyComponent extends Component {
2 render() {
3 return (
4 <div>
5 <input ref={input => this.myInput = input} />
6 </div>
7 );
8 }
9}
从那里,您可以通过this.myInput
访问该元素,您可以使用几种方法。
使用Refs来获取输入的价值
它就像访问元素的值
一样简单,就像是2005年。
1class MyComponent extends Component {
2 alertInput() {
3 const value = this.myInput.value;
4 // Please don't use alert in actual applications.
5 alert(value);
6 }
7
8 render() {
9 return (
10 <div>
11 <input ref={input => this.myInput = input} />
12 <button onClick={this.alertInput.bind(this)}>Alert</button>
13 </div>
14 );
15 }
16}
<$>[注]如果你正在使用Redux,你可能想要使用一个受控的组件,但它是方便的知道一个快速的演示。
<$>[注意]设置值
不会结束;当元素重新渲染时,React 会删除元素。
使用 Refs 来集中输入
管理焦点可能是反馈的最常见用例之一,如果只是因为没有好的替代品。
1class MyComponent extends Component {
2 // As soon as the component mounts, `myInput` will be focused.
3 componentDidMount() {
4 this.myInput.focus();
5 }
6
7 render() {
8 return (
9 <div>
10 <input ref={input => this.myInput = input} />
11 </div>
12 );
13 }
14}
使用 Refs 来操纵一个 Canvas
面料不太有用,除非有面料元素可以相互作用。
1class MyComponent extends Component {
2 // The canvas is drawn when the component is mounted.
3 componentDidMount() {
4 this.drawCanvas();
5 }
6
7 // The canvas is drawn when the component updates.
8 componentDidUpdate() {
9 this.drawCanvas();
10 }
11
12 drawCanvas() {
13 const context = this.myCanvas.getContext('2d');
14 context.clearRect(0, 0, 500, 500);
15 context.fillText('If you can read this, your eyes are better than mine.', 250, 250);
16 }
17
18 render() {
19 return (
20 <div>
21 <canvas ref={canvas => this.myCanvas = canvas} height={500} width={500} />
22 </div>
23 );
24 }
25}
<$>[注] 请记住在更新时重新绘制面板。