【问题标题】:ReactJS: Accessing child components properties in parentReactJS:访问父组件中的子组件属性
【发布时间】:2023-07-24 06:43:01
【问题描述】:

我正在尝试用 React 包装语义 ui 元素,以便它们可以在我的应用程序中重复使用。

var s_input = React.createClass({
        render: function(){
            return this.transferPropsTo(
                <div className = "ui input">
                    <input type="text" placeholder={this.props.placeHolderTxt} ref="text"/>
                </div>
            )
        }
    });

我在 from: 中使用输入组件:

<form onSubmit={this.handleSubmit} method="POST">
    <s_input placeHolder={this.props.placeHolderTxt||''}></s_input>
</form>

这是我的 handleSubmit 方法:

handleSubmit:function(e){
    e.preventDefault();
    var text = this.refs.text.getDOMNode().value.trim();
               this.refs.text.getDOMNode().value = '';
               this.props.onSubmit(text);
}

我遇到的问题是在提交表单时尝试访问 input 组件的 text 属性,以便我可以执行this.refs.text.getDOMNode().value.trim(); 之类的操作。有没有人知道如何去做。

【问题讨论】:

  • 你能展示完整的handleSubmit()方法吗?
  • 我已经编辑了问题并包含了我的 handleSubmit() 代码

标签: reactjs


【解决方案1】:

你可以这样做

var input = React.createClass({
    render: function(){
        return this.transferPropsTo(
            <div className = "ui input">
                <input className="ui input" type="text" placeHolder={this.props.placeHolderTxt} ref="text"/>
            </div>
        )
    },
    getValue: function() {
        return this.refs.text.getDOMNode().value;
    }
});

然后你可以做&lt;s_input ref="myinput" /&gt;this.refs.myinput.getValue()。您还可以构建代码以传递 onChange 回调,然后像处理任何其他受控组件一样读取e.target.valueForms

【讨论】:

  • 谢谢!!为我工作!
最近更新 更多