javascript - 如何在div onClick中获取元素的文本内容? React.js、JavaScript

标签 javascript reactjs

我想在点击时获取div的文本内容。

我尝试将引用添加到我的语法中,但当我尝试执行 const ref = this.refName.textContent 时,它不起作用。

所以我想要实现的是点击recipe-container,将h3ul的文本内容存储到变量中,其中变量位于父组件中。

这是我的子组件:

export default class Recipecontainer extends React.Component {
render(){
    const recipe = this.props.recipe;
    let recipeIngredients = recipe.ingredients;
    recipeIngredients = recipeIngredients.map((item, index) => <li key={index}>{item}</li>);
    return (
        <div className="recipe-container">
            <h3 className="recipe-name">{recipe.recipeName}</h3>
            <div className="food-img">
                <img src={recipe.smallImageUrls} alt=""/>
            </div>
            <ul className="ingredient-list">{recipeIngredients}</ul>
        </div>
    )
}

这是我计划使用的方法,在我的父组件中,将这些文本内容保存到变量中;但当然我下面写的不起作用。

saveData(e){
    const recipeName = document.getElementsByClassName(".recipe-name").textContent;
}

感谢任何帮助!

最佳答案

使用innerHTML代替textCOntent

 const recipeName = document.getElementsByClassName(".recipe-name").innerHTML;

关于javascript - 如何在div onClick中获取元素的文本内容? React.js、JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48251104/

相关文章:

javascript - CSS\JS\JQuery : Customize color of clicked (not chosen) option in multiselect box

javascript - 指向分支时如何解决 "Cannot find module"?

javascript - React - 在渲染之前加载数据

reactjs - react-chartjs-2 保持 x 轴始终为 0% 到 100%

javascript - For 循环 : Iterating via character - Javascript

javascript - 使用 jQuery 在单击的按钮上方添加内容时防止页面移动

javascript - 如何给antd Select设置自定义样式?

javascript - Provider使用一次就够了吗?

javascript - Cloudant/CouchDB 是否可以创建一个 View 来检查是否有重复项?

javascript - 像面向对象编程一样将组件作为实例进行 react