【发布时间】:2019-12-19 13:25:59
【问题描述】:
我有一个 TextInput 组件在几个不同的地方被重用:
export default class SomeTextInput extends Component {
constructor(props) {
super(props);
}
render() {
let fontWeight = this.props.fontWeight ? this.props.fontWeight : 'Light';
let fontName = this.props.fontName ? this.props.fontName : 'Montserrat';
let fontString = createFontString(fontName, fontWeight);
let applyFontFamily = { fontFamily: fontString };
let style = this.props.style.constructor === Array ? this.props.style : [this.props.style];
return (
<TextInput
ref={(ref) => {
this.textInput = ref
}}
{...this.props}
style={[applyFontFamily, ...style]}
onFocus={() => {
this.clearText();
console.log('show me this.textInput', this.textInput.props.placeholder)
}}
/>
)
}
clearText() {
this.textInput.clear();
console.log('is this being reached???')
}
focus() {
this.textInput.focus();
}
blur() {
this.textInput.blur();
}
}
我也尝试过使用clearTextOnFocus。我认为最好的方法是将placeholder 更改为'',但我不确定placeholder 文本是如何取自已被传递下来的prop。
编辑:我将添加@ravibagul91 建议的代码
export default class OVTextInput extends Component {
constructor(props) {
super(props);
// this.state = {
// placeholder: props.placeholder
// }
}
render() {
let fontWeight = this.props.fontWeight ? this.props.fontWeight : 'Light';
let fontName = this.props.fontName ? this.props.fontName : 'Montserrat';
let fontString = createFontString(fontName, fontWeight);
let applyFontFamily = { fontFamily: fontString };
let style = this.props.style.constructor === Array ? this.props.style : [this.props.style];
return (
<TextInput
ref={(ref) => {
this.textInput = ref
}}
{...this.props}
style={[applyFontFamily, ...style]}
onFocus={() => {
// this.setState({ placeholder: "" });
this.clearText();
}}
/>
)
}
clearText = () => {
console.log(this.textInput)
console.log('is this being reached???', this.textInput.value);
console.log('is this being reached???', this.textInput.placeholder);
this.textInput.placeholder = "";
this.textInput.value = "";
}
// focus = () => {
// this.textInput.focus();
// }
// blur = () => {
// this.textInput.blur();
// }
focus() {
this.textInput.focus();
}
blur() {
this.textInput.blur();
}
};
【问题讨论】:
-
您的意思是要删除占位符,而不是文本?
-
我希望占位符文本在输入聚焦时消失。目前,文本仅在我开始输入时才会消失
-
@VK1 也试试我的解决方案,如果有帮助,请告诉我。
-
我尝试了您的解决方案。 this.textInput.value 和 this.texInput.placeholder 在 console.logs 中返回为 undefined
-
你把它们当作道具传递了吗?请参阅我的演示,我已将值和占位符作为道具传递。如果不想通过,可以直接手动写占位符。
标签: react-native textinput ref