在将ref添加到TextInput之后,我收到一条警告:“无法为无状态功能组件提供ref。尝试访问此ref将会失败”,并且我无法集中精力处理TextInput。为什么它不起作用。
import { CustomUrlSerialize } from path-to-the-file // Import the file
const customUrlSerializer = new CustomUrlSerialize();
const CustomUrlSerializerProvider = {
provide: UrlSerializer,
useValue: customUrlSerializer
};
@NgModule({
declarations: [
AppComponent,
...
],
imports: [
CommonModule,
BrowserModule,
BrowserAnimationsModule,
...
],
providers: [CustomUrlSerializerProvider] // <-- Add this as a provider
})
export class AppModule { }
已更新:我更新了代码以更好地理解。
答案 0 :(得分:0)
为了使用ref={(input) => { this.textInput = input; }}
和onChangeText={(username) => this.setState({ username })}
,您不能使用无状态组件。您可以使用PureComponent或Component。我认为您应该使用PureComponent。另外,您还必须添加一个构造函数以初始化状态。试试这个:
import React, {PureComponent} from 'react';
class YourComponentName extends PureComponent {
constructor(){
super()
this.state={
username:'',
password:''
}
}
render() {
return (
//Your render function code
.
.
.
<TextInput
style={styles.input}
placeholder="Username"
returnKeyType="next"
placeholderTextColor="grey"
onSubmitEditing={(event)=>this.textInput.focus()}
onChangeText={(username) => this.setState({ username })}
blurOnSubmit={false}
value={this.state.username}
/>
.
.
.
<TextInput
style={styles.input}
placeholder="Password"
placeholderTextColor="grey"
underlineColorAndroid={'transparent'}
onChangeText={(password) => this.setState({ password })}
ref={(input) => { this.textInput = input; }}
returnKeyType="done"
value={this.state.password}
secureTextEntry={true}
blurOnSubmit={true}
/>
);
}
}
答案 1 :(得分:0)
抱歉,耽搁了。您可以在不使用引用的情况下执行此操作。尝试通过状态组件使用这种方法:
export default class LoginScreen extends Component {
constructor(props) {
super(props);
this.state = {
username: '',
password: '',
focusPasswordInput: false,
};
}
handleUsernameInputSubmit() {
this.setState({
focusPasswordInput:true
});
}
render()
{
return (
<View style={{flex: 1}}>
<ScrollView ref="scrollView" style={[styles.container]}>
<View style={styles.inputField}>
<Image
source={require('../images/username.png')}
style={[styles.icon]}
/>
<TextInput
style={styles.input}
placeholder="Username"
returnKeyType="next"
placeholderTextColor="grey"
onSubmitEditing={() => this.handleUsernameInputSubmit()}
onChangeText={(username) => this.setState({
username
})}
blurOnSubmit={false}
value={this.state.username}
/>
</View>
<View style={styles.inputField}>
<Image
source={require('../images/password.png')}
style={[styles.icon]}
/>
<TextInput
style={styles.input}
placeholder="Password"
placeholderTextColor="grey"
underlineColorAndroid={'transparent'}
onChangeText={(password) => this.setState({password})}
focus={this.state.focusPasswordInput}
returnKeyType="done"
value={this.state.password}
secureTextEntry={true}
blurOnSubmit={true}
/>
</View>
</ScrollView>
</View>
)
}
}