我试图弄清楚我需要如何使用React.createRef()打字稿来响应本机,因为以下代码会引发错误
// ...
circleRef = React.createRef();
componentDidMount() {
this.circleRef.current.setNativeProps({
someProperty: someValue
});
}
// ...
Run Code Online (Sandbox Code Playgroud)
目前抛出以下错误 this.circleRef.current.setNativeprops
[ts] 对象可能为“空”。(属性) React.RefObject<{}>.current: {} | 空值
和
[ts] 类型“{}”上不存在属性“setNativeProps”。任何
有任何想法吗?
我很难在上下文提供程序中设置引用。这是不可能的还是我遗漏了什么?我能够以相同的方式在其他组件中 createRefs 但以下始终将 ref 显示为 { current: null }
const VideoPlayerContext = React.createContext();
export default class VideoPlayerProvider extends Component {
videoPlayerComponent = React.createRef()
state = {
// some state
}
seek = (time) => {
this.videoPlayerComponent.seek(time)
}
render () {
return (
<VideoPlayerContext.Provider value={Object.assign({}, this.state, { seek: seek})}>
<VideoPlayer
key={'videoplayer'}
{...this.state}
ref={this.videoPlayerComponent}
/>
{ this.props.children }
</VideoPlayerContext.Provider>
)
}
}
Run Code Online (Sandbox Code Playgroud)
然后我的应用程序就这样包装了
const app = () => (
<VideoPlayerProvider>
<App />
</VideoPlayerProvider>
)
Run Code Online (Sandbox Code Playgroud)
任何帮助表示赞赏!
我正在使用 TypeScript 构建 React 应用程序。
我想创建按钮,滚动到主页上子组件的标题。
我已经在子组件中创建了一个引用,遵循此堆栈溢出答案,并(尝试)使用前向引用在我的父组件上访问它。
export class Parent extends Component {
private testTitleRef!: RefObject<HTMLHeadingElement>;
scrollToTestTitleRef = () => {
if (this.testTitleRef.current !== null) {
window.scrollTo({
behavior: "smooth",
top: this.testTitleRef.current.offsetTop
});
}
};
render() {
return <Child ref={this.testTitleRef} />
}
}
interface Props {
ref: RefObject<HTMLHeadingElement>;
}
export class Child extends Component<Props> {
render() {
return <h1 ref={this.props.ref}>Header<h1 />
}
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,当我触发时,scrollToTestTitleRef我收到错误:
Cannot read property 'current' of undefined
Run Code Online (Sandbox Code Playgroud)
这意味着 ref 未定义。这是为什么?我究竟做错了什么?
编辑: Estus …
我在同时使用refvia connect 和 redux-form时遇到问题。
组件的结构使得ChildComponent具有 Forms 并且我正在使用
class EditEvent extends Component {
constructor (props) {
super(props);
this.handleStartDateChange = this.handleStartDateChange.bind(this);
this.handleEndDataChange = this.handleEndDataChange.bind(this);
this.state = {loading: false};
}
componentDidMount(){
this.props.fetchEvent(this.props.session,true);
this.props.fetchScheduleDates(this.props.session);
}
submitSettings(){
this.props.form.submit();
}
handleStartDateChange(date) {
this.props.updateUnsavedChanges();
this.props.dateRangeUpdate({startDate:date,endDate:date,allDate:{}});
}
handleEndDataChange(date) {
this.props.updateUnsavedChanges();
this.props.dateRangeUpdate({startDate:this.props.scheduledates.startDate,endDate:date,allDate:{}});
}
renderBlockList(startDate,endDate,allDate){
/*if(isEmpty(allDate)){
return 'Please select date duration first.';
}*/
var arr = [];
var day = {};
var n = endDate.diff(startDate,'days')+1;
for (var i=1; i <= n; i++ ) {
if(i …Run Code Online (Sandbox Code Playgroud) 我有一个 React 功能组件,可以递归地呈现嵌套列表。那部分工作正常。
我正在努力解决的部分是让包含嵌套列表的 div 在嵌套列表(不同大小)出现和消失时具有扩展动画。
由于内容量未知,因此简单地对 max-height 属性进行动画处理是行不通的。例如,当渲染一级列表时,框架的高度可能会扩展到 100px。但是,如果将 max-height 设置为 100px,则 div 以后将无法扩展以容纳越来越多扩展的嵌套列表。
<div className="frame"> [nested ordered lists] </div>
Run Code Online (Sandbox Code Playgroud)
同样,我之前尝试过在 max-height 属性上使用 CSS 过渡,但这远不是理想的解决方案,因为它在不可预测的高度上效果不佳。所以,如果可能的话,我不想那样做。
我遵循了一个教程,并让它在没有 React 的情况下使用普通 JavaScript 工作(部分代码被注释掉),但是当将其翻译为 React 时,我不确定为什么我无法让代码工作。
目前,展开动画正在工作,但如果边框被删除或更改为白色,它将停止工作。我不知道为什么。??
** 另外,折叠动画根本不起作用。“transitioned”事件并不总是在 ref 对象上触发,有时会在它应该被删除后触发。
有人能帮助我指出正确的方向吗?
(我尝试将其转移到 JS Fiddle,但它不起作用)。
(codepen 的另一次尝试,供参考。嵌套列表出现和消失,但没有转换)。 https://codepen.io/maiya-public/pen/MWgGzBE
这是原始代码:(我认为在 codepen 上更容易理解,但粘贴到这里是为了更好的实践)。
索引.html
<div id="root">
</div>
Run Code Online (Sandbox Code Playgroud)
样式.css
.frame {
overflow:hidden;
transition: all 0.5s ease-out;
height:auto;
// for some reason,without the border, not all of them will transition AND it …Run Code Online (Sandbox Code Playgroud) 我有两个组件。一个父母和一个孩子。
在父组件内,我有一个按钮。如果用户单击该按钮,我想对子组件内的另一个按钮执行 ScrollIntoView。
我想我想定义对子按钮 a 的引用,以便我在父按钮 onClick 中可以执行以下操作:
ref.scrollIntoView({block: 'end', behavior: 'smooth'});
Run Code Online (Sandbox Code Playgroud)
这将滚动到子组件中的按钮。
这是一个缩小的例子:
import React, {useRef} from 'react';
import ChildComponent from './ChildComponent';
const ParentComponent = props => {
const childReference = useRef(null);
const onClick = () => {
childReference.scrollIntoView({block: 'end', behavior: 'smooth'});
}
return (
<>
<...some other components>
<Button onClick={onClick}>Click me to be forwarded</Button>
<ChildComponent ref={childReference}/>
</>
);
};
Run Code Online (Sandbox Code Playgroud)
import React from 'react';
const ChildComponent = (props, ref) => {
const { name, value, description } …Run Code Online (Sandbox Code Playgroud) 这是一个关于在规范中使用 React refs 的问题。具体来说,我在浏览器中看到的行为与在测试中运行时看到的行为不同。
// app_container.test.js
import React from 'react'
import ReactDOM from 'react-dom'
import AppContainer from "./app_container"
import { render, fireEvent, waitForElement, cleanup, wait } from '@testing-library/react'
import '@testing-library/jest-dom/extend-expect'
import axiosMock from 'axios'
import { useAsync } from "react-use"
afterEach(cleanup);
test("renders", () => {
const { getByTestId } = render(<AppContainer />);
expect(getByTestId("app-container")).toHaveClass("app-container");
});
test("when mounted, it loads the rings", async () => {
jest.setTimeout(15000);
const { getByTestId } = render(<AppContainer />);
const container = getByTestId('app-container')
await wait(() => expect(getByText("Abc")).toBeInTheDocument()); …Run Code Online (Sandbox Code Playgroud) 考虑到我有一个使用一个或多个refsDOM 元素的自定义钩子,我看到了两种不同的方式来编写/使用这样的钩子(而且我知道可能还有更多细微差别 \xe2\x80\x93 例如回调引用)。
选项 1:从自定义挂钩返回ref并在组件中使用它:
const Option1 = () => {\n const hooksRef = myCustomHookReturninARef()\n \n return <div ref={hooksRef}>Using returned ref as prop.</div>\n}\nRun Code Online (Sandbox Code Playgroud)\n选项 2ref :在组件中创建一个并将其传递给自定义挂钩:
const Option2 = () => {\n const componentsRef = React.createRef()\n \n myCustomHookExpectingRefArgument(componentsRef)\n \n return <div ref={componentsRef}>Using created ref as prop..</div>\n}\nRun Code Online (Sandbox Code Playgroud)\n我一直在使用这两个选项,它们似乎都工作得很好。我知道这可能是一个固执己见的问题,但是:
\n使用第一种方法与第二种方法相比是否有一些明显的缺点?
\n我使用BottomSheetModal在底部工作表中显示所有国家/地区的列表。'BottomSheetModalInternalContext' cannot be null!但是,当导航到包含底部模式的屏幕时,我收到错误消息。
我假设发生错误是因为我bottomSheetModalRef用 null 初始化 ref ( ) ,但我不知道如何在不传入 null 的情况下创建 ref 。
完整错误消息的摘录
'BottomSheetModalInternalContext' cannot be null!
This error is located at:
in ForwardRef(BottomSheetModal)
in ForwardRef(BottomSheetModal) (at CountryPicker.tsx:89)
in RCTView (at View.js:34)
in View (created by ForwardRef)
in ForwardRef (at CountryPicker.tsx:74)
...
Run Code Online (Sandbox Code Playgroud)
//CountryPicker.tsx
import React, { useRef, useState, useEffect, useMemo } from 'react'
import {
ActivityIndicator,
TextInput,
TouchableOpacity,
StyleSheet,
} from 'react-native'
import axios from 'axios'
import { BottomSheetFlatList, BottomSheetModal } …Run Code Online (Sandbox Code Playgroud) 我正在学习如何在这里使用前向引用,我有一个 FC,我需要在其中初始化所有引用,然后将它们传递给它的子级,以便我可以获得一些 Chartjs 图表的画布实例。然而,使用forwardRef我得到一个类型错误,说ref不是孩子的属性。
const BUIDashboard: React.FC = () => {
const chartRef = React.createRef<RefObject<HorizontalBar>>()
.
.
.
return (
<Child
ref={chartRef} <------------------- TYPE ERROR HERE
isLoading={isLoadingChild}
data={childData} />
)
}
Run Code Online (Sandbox Code Playgroud)
孩子没有错误,但它是这样设置的
type Props = {
rootProps?: DashboardCardProps
isLoading?: boolean
data?: BUIMetrics['breachBreakdownByOutcome']
}
const Child: React.FC<Props> = React.forwardRef(({ rootProps, isLoading, data }, ref: RefObject<HorizontalBar>) => {
return (
<HorizontalBar ref={ref}/>
)
}
Run Code Online (Sandbox Code Playgroud)
我是否错误地为孩子定义了参数?
我认为问题可能出在这一行
const Child: React.FC<Props>
Run Code Online (Sandbox Code Playgroud)
所以我将 Props 类型更新为
type Props = {
rootProps?: DashboardCardProps
isLoading?: boolean
data?: BUIMetrics['breachBreakdownByOutcome'] …Run Code Online (Sandbox Code Playgroud) react-ref ×10
reactjs ×9
javascript ×4
react-native ×3
typescript ×3
react-hooks ×2
animation ×1
jestjs ×1
react-redux ×1
recursion ×1
redux-form ×1
use-ref ×1