Reactjs 在React中的无状态函数组件中选择React中的元素?
但我得到了一个错误:Reactjs 在React中的无状态函数组件中选择React中的元素?,reactjs,Reactjs,但我得到了一个错误: componentWillMount = () => { this.refs.questionInput.focus(); console.log('test') } } 那么,有没有办法在React中聚焦输入字段而不使用ref?没有,您需要更改 您不能在功能组件上使用ref属性,因为它们没有实例 您还应该使用较新的回调API来设置ref: Stateless function components cannot have
componentWillMount = () => {
this.refs.questionInput.focus();
console.log('test')
}
}
那么,有没有办法在React中聚焦输入字段而不使用ref?没有,您需要更改 您不能在功能组件上使用ref属性,因为它们没有实例 您还应该使用较新的回调API来设置ref:
Stateless function components cannot have refs.
或者对于v16.3
如果您只想将注意力集中在挂载上,那么将自动对焦
道具添加到输入组件中可能会奏效:
ref={ref => { this.questionInput = ref }}
是。然而,您使用
ref
的方法确实过时了。您应该更新到React的最新版本(当前为16.3.2
),并遵循
功能自定义文本输入(道具){
//textInput必须在此处声明,以便ref可以引用它
让textInput=React.createRef();
函数handleClick(){
textInput.current.focus();
}
返回(
);
}
您应该用函数包装输入组件。大概是这样的:
<TextField
onChange={props.onChangeTextField}
ref="questionInput"
style={styles.textField}
value={props.existingValue}
fullWidth={true}
/>
function CustomTextInput(props) {
// textInput must be declared here so the ref can refer to it
let textInput = React.createRef();
function handleClick() {
textInput.current.focus();
}
return (
<div>
<input
type="text"
ref={textInput} />
<input
type="button"
value="Focus the text input"
onClick={handleClick}
/>
</div>
);
}
import*as React from“React”;
const TextInput=React.forwardRef(
(道具,参考)=>
);
导出默认文本输入;
请注意,它将向函数组件添加第二个参数,您应该将其作为
ref
prop.传递给DOM元素。React建议与componentDidMount中的DOM进行交互。您能提供多一点代码吗?哪个组件是功能组件?你到底想什么时候控制它的焦点状态?那么我如何聚焦元素?你说的“我如何聚焦元素”是什么意思您是说从父元素控制元素的焦点状态吗?文档中的第一句话链接到状态:您不能在功能组件上使用ref属性,因为它们没有实例:@maxwell Yes,但是“但是,只要引用DOM元素或类组件,就可以在功能组件内使用ref属性。”他的问题的核心不是“我可以将ref
直接放在功能组件上吗?”而是“我可以使用ref
将元素集中在功能组件内吗?”。“是的,他能做到。”事实上-我猜父对象不重要-是的,向下缩回Votei是否可以在没有参考的情况下聚焦元素?请尝试自动聚焦
道具。仅用于初始关注。不确定这是否真正解决了问题。但不太清楚OP的要求是什么。我想我理解作者的要求。他们希望ref具有.focus()
属性,就像它是DOM元素一样,但是当您将ref传递给组件时,您会得到组件实例,或者在功能组件的情况下会得到警告。在引入中间组件但还需要能够访问DOM元素实例的情况下,Ref转发非常有用。这是问题的解决方案,但另一种解决方案是创建Ref并将其传递给无状态函数组件。
function CustomTextInput(props) {
// textInput must be declared here so the ref can refer to it
let textInput = React.createRef();
function handleClick() {
textInput.current.focus();
}
return (
<div>
<input
type="text"
ref={textInput} />
<input
type="button"
value="Focus the text input"
onClick={handleClick}
/>
</div>
);
}
import * as React from "react";
const TextInput = React.forwardRef(
(props, ref) => <input ref={ref} {...props} />
);
export default TextInput;