reactjs - this.refs x useRef(有什么相似之处吗?)
问题描述
我正在尝试使用一个使用 this.ref 的库,但我必须将它传递给钩子。我不明白。
原始代码:
import ViewShot from "react-native-view-shot";
class ExampleCaptureOnMountManually extends Component {
componentDidMount () {
this.refs.viewShot.capture().then(uri => {
console.log("do something with ", uri);
});
}
render() {
return (
<ViewShot ref="viewShot" options={{ format: "jpg", quality: 0.9 }}>
<Text>...Something to rasterize...</Text>
</ViewShot>
);
}
}
我的钩子代码:
export default function screenshot() {
const refs = useRef();
refs.viewShot.capture().then(uri => {
console.log('do something with ', uri);
});
return (
<View style={styles.container}>
<View style={styles.header} />
<ViewShot ref="viewShot" options={{format: 'jpg', quality: 0.9}}>
<View>
<Text>Hello World</Text>
</View>
</ViewShot>
<View style={styles.footer}>
<Button title="print" onPress={onCapture} />
</View>
</View>
);
}
解决方案
使用useRef()
,你不这样做const refs = useRef();
,你声明 ref:
const viewShot = useRef();
然后在ref
属性中传递它:
<ViewShot ref={viewShot} ...
您现在应该将其用作viewShot.current
.
尽管如此,由于您的原始代码在 中执行componentDidMount
,现在您还应该使用useEffect
(注意添加.current
):
useEffect(() => {
viewShot.current.capture().then(uri => {
console.log('do something with ', uri);
});
}, [])
所以:
export default function screenshot() {
const viewShot = useRef();
useEffect(() => {
viewShot.current.capture().then(uri => {
console.log('do something with ', uri);
});
}, [])
return (
<View style={styles.container}>
<View style={styles.header} />
<ViewShot ref={viewShot} options={{format: 'jpg', quality: 0.9}}>
<View>
<Text>Hello World</Text>
</View>
</ViewShot>
<View style={styles.footer}>
<Button title="print" onPress={onCapture} />
</View>
</View>
);
}
推荐阅读
- python - Tensorflow 替换张量中接近于零的值
- puppet - 在 Windows 上安装包失败;'安装过程中的致命错误'
- html - 如何防止文本从跨度进入兄弟跨度的内容?
- reactjs - React 检查组件重新渲染的次数
- node.js - 如何使用节点将我的 CSS 和 index.html 文件托管到我的本地服务器中
- dagger-2 - 用于封装的 Dagger 2 子组件
- fscalendar - 在 FSCalendar 中,如何在没有 reloadData 的情况下刷新最小日期
- android - 显示多个列表的有效方式
- sql - 如何优化 SQL 查询性能
- python - Keras 自定义损失:将值汇集到直方图中